春天注释混乱

时间:2015-07-29 13:09:23

标签: java spring

我真的很困惑春天的注释。 在哪里使用@Autowired,其中class是@ Bean或@Component,

我知道我们不能使用

 Example example=new Example("String"); 
春天

但是如何孤独

@Autowired
Example example;

会解决目的吗? 那么Example Constructor,spring将如何为Example Constructor提供String值?

我浏览了一篇文章,但这对我来说没什么意义。 如果有人能给我简单而简单的解释,那就太好了。

3 个答案:

答案 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
相关问题