我真的很困惑春天的注释。 在哪里使用@Autowired,其中class是@ Bean或@Component,
我知道我们不能使用
Example example=new Example("String");
春天但是如何孤独
@Autowired
Example example;
会解决目的吗? 那么Example Constructor,spring将如何为Example Constructor提供String值?
我浏览了一篇文章,但这对我来说没什么意义。 如果有人能给我简单而简单的解释,那就太好了。
答案 0 :(得分:3)
Spring并没有说你不能做Example example = new Example("String");
如果Example
不需要是一个单独的bean,那么这仍然是完全合法的。 @Autowired
和@Bean
发挥作用的地方是您希望将类实例化为单例。在Spring中,只要正确设置了组件扫描,使用@Service
,@Component
或@Repository
注释的任何bean都将自动注册为单例bean。使用@Bean
的选项允许您定义这些单例,而无需明确注释类。相反,您将创建一个类,使用@Configuration
对其进行注释,并在该类中定义一个或多个@Bean
定义。
所以而不是
@Component
public class MyService {
public MyService() {}
}
你可以
public class MyService {
public MyService() {}
}
@Configuration
public class Application {
@Bean
public MyService myService() {
return new MyService();
}
@Autowired
@Bean
public MyOtherService myOtherService(MyService myService) {
return new MyOtherService();
}
}
权衡是将bean定义在一个地方,而不是注释个别类。我通常根据我的需要使用两者。
答案 1 :(得分:2)
首先定义一个类型为bean的bean:
<beans>
<bean name="example" class="Example">
<constructor-arg value="String">
</bean>
</beans>
或在Java代码中:
@Bean
public Example example() {
return new Example("String");
}
现在当你使用@Autowired
时,spring容器会将上面创建的bean注入到父bean中。
答案 2 :(得分:1)
默认构造函数+ @Component
- 注释足以让@Autowired
工作:
@Component
public class Example {
public Example(){
this.str = "string";
}
}
您永远不应通过@Bean
声明实例化具体实现。总是做这样的事情:
public interface MyApiInterface{
void doSomeOperation();
}
@Component
public class MyApiV1 implements MyApiInterface {
public void doSomeOperation() {...}
}
现在您可以在代码中使用它:
@Autowired
private MyApiInterface _api; // spring will AUTOmaticaly find the implementation