我知道在spring 2.5中引入@Component注释是为了通过使用类路径扫描来摆脱xml bean定义。
@Bean是在spring 3.0中引入的,可以和@Configuration一起使用,以便完全摆脱xml文件,而使用java配置。
是否有可能重用@Component注释而不是引入@Bean注释?我的理解是,最终目标是在这两种情况下都创建bean。
我知道在spring 2.5中引入@Component注释是为了通过使用类路径扫描来摆脱xml bean定义。
@Bean是在spring 3.0中引入的,可以和@Configuration一起使用,以便完全摆脱xml文件,而使用java配置。
是否有可能重用@Component注释而不是引入@Bean注释?我的理解是,最终目标是在这两种情况下都创建bean。
当前回答
@Bean可以有作用域,而@component不能 如 @Scope(value = WebApplicationContext.)SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
其他回答
@Component和@Bean做两件完全不同的事情,不应该混淆。
@Component(以及@Service和@Repository)用于使用类路径扫描自动检测和自动配置bean。在带注释的类和bean之间存在隐式的一对一映射(即每个类一个bean)。这种方法对连接的控制非常有限,因为它是纯声明性的。
@Bean用于显式地声明单个bean,而不是像上面那样让Spring自动执行。它将bean的声明与类定义解耦,并允许您按照自己的选择创建和配置bean。
回答你的问题…
是否有可能重用@Component注释而不是引入@Bean注释?
当然,可能;但他们选择不这样做,因为这两者是完全不同的。春天已经够让人迷惑了,不要再把水弄脏了。
假设我想要特定的实现依赖于某种动态状态。 @Bean非常适合这种情况。
@Bean
@Scope("prototype")
public SomeService someService() {
switch (state) {
case 1:
return new Impl1();
case 2:
return new Impl2();
case 3:
return new Impl3();
default:
return new Impl();
}
}
然而,@Component没有办法做到这一点。
当您使用@Component标记时,这与使用带有香草bean声明方法(用@Bean注释)的POJO(普通旧Java对象)是一样的。例如,下面的方法1和2将给出相同的结果。
方法1
@Component
public class SomeClass {
private int number;
public SomeClass(Integer theNumber){
this.number = theNumber.intValue();
}
public int getNumber(){
return this.number;
}
}
用豆子表示“数字”:
@Bean
Integer theNumber(){
return new Integer(3456);
}
方法2
//Note: no @Component tag
public class SomeClass {
private int number;
public SomeClass(Integer theNumber){
this.number = theNumber.intValue();
}
public int getNumber(){
return this.number;
}
}
两者都有豆子:
@Bean
Integer theNumber(){
return new Integer(3456);
}
@Bean
SomeClass someClass(Integer theNumber){
return new SomeClass(theNumber);
}
方法2允许您将bean声明放在一起,它更加灵活。您甚至可能想要添加另一个非香草SomeClass bean,如下所示:
@Bean
SomeClass strawberryClass(){
return new SomeClass(new Integer(1));
}
我看到了很多答案,几乎每个地方都提到@Component用于自动装配组件,而@Bean恰恰是在声明要以不同的方式使用bean。让我来展示它的不同之处。
@ bean
首先,它是一个方法级注释。 其次,通常使用它在Java代码中配置bean(如果不使用xml配置),然后使用类从类中调用它 ApplicationContext。getBean方法。例子:
@Configuration
class MyConfiguration{
@Bean
public User getUser() {
return new User();
}
}
class User{
}
// Getting Bean
User user = applicationContext.getBean("getUser");
@ component
这是注释bean的一般方法,而不是专门的bean。 它是一个类级注释,用于避免通过java或xml配置进行所有配置。
我们得到这样的结果。
@Component
class User {
}
// to get Bean
@Autowired
User user;
就是这样。引入它只是为了避免实例化和使用该bean的所有配置步骤。
@Bean可以有作用域,而@component不能 如 @Scope(value = WebApplicationContext.)SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)