繁体   English   中英

Spring注解混乱

[英]Spring annotations confusion

我真的对Spring注释感到困惑。 在哪里使用@ Autowired,在哪里使用@ Bean或@ Component,

我知道我们不能使用

 Example example=new Example("String"); 

在春天,但多么孤独

@Autowired
Example example;

将解决目的? 那么示例构造函数呢,spring如何将字符串值提供给示例构造函数?

我读了一篇文章,但对我来说没有多大意义。 如果有人可以给我简单而简短的解释,那就太好了。

Spring不会说你不能做Example example = new Example("String"); 如果Example不需要是单例bean,那仍然是完全合法的。 @Autowired@Bean发挥作用的地方是当您要实例化一个单例类时。 在Spring中,只要正确设置了组件扫描,用@Service @Repository@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定义在一个地方,而不是注释单个类。 我通常根据需要使用两者。

首先,您将定义一个类型为example的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中。

默认构造函数+ @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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM