我是 Spring 的初学者。我已经浏览了一些在线教程并编写了一个简单的程序,但我无法理解其值(value)。当我们使用 spring.xml 文件并使用 getBean 方法创建对象时。但是,在注释的情况下,我使用 new 创建对象,我认为这是不对的。请查看下面的代码,并让我知道我所遵循的过程是否有问题。
Hello.java:
package bean;
import org.springframework.stereotype.Component;
@Component
public class Hello {
String gender;
public void print(){
System.out.println("Hello world "+gender);
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
AppConfig.java:
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import bean.Hello;
@Configuration
public class AppConfig {
@Bean(name="h")
public Hello getHello(){
Hello h= new Hello();
h.setGender("male");
return h;
}
}
Driver.java:
package client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import bean.Hello;
import config.AppConfig;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);
Hello h=ct.getBean("h",Hello.class);
h.print();
}
}
正如您在 AppConfig.java 中看到的,我正在使用
创建类的对象Hello h= new Hello();
这看起来有问题。如果我必须自己创建对象,那为什么我们需要 spring.请建议我在这里做错了什么。
最佳答案
有两种方法可以在 Spring Context 中创建 bean
- 使用@Component注解(委托(delegate)创建Spring框架)
@Component:类上方的注释表明该类是一个组件,应该被自动检测和实例化。因此 Spring 组件 bean 将如下所示:
@Component
public class User {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
使用组件扫描来扫描你的bean:
Xml 老派 Spring 配置:
<context:component-scan base-package=”com.yourpackage” />
组件扫描(如果您使用Spring boot,它将包含在@SpringBootAppilcation中)
@ComponentScan(basePackageClasses = Yourclass.class)
- 使用@Configuration注释:(您的实际选择)
使用@Configuration类和用@bean注释的方法。您应该在此处提供如何创建新的对象设置值(您的 getHello 方法):
@Bean(name="h")
public Hello getHello(){
Hello h= new Hello();
h.setGender("male");
return h;
}
关于java - 使用 spring 注解创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52809099/