【问题标题】:Spring annotations confusionSpring注解混乱
【发布时间】:2015-10-20 11:44:21
【问题描述】:

我真的对 spring 注释感到困惑。 在哪里使用@Autowired,其中class是@Bean还是@Component,

我知道我们不能使用

 Example example=new Example("String"); 

在春天 但如何孤独

@Autowired
Example example;

会解决的目的吗? 那么 Example Constructor 呢,spring 是如何给 Example Constructor 提供 String 值的呢?

我浏览了其中一篇文章,但对我来说没有多大意义。 如果有人能给我简短的解释,那就太好了。

【问题讨论】:

标签: java spring


【解决方案1】:

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

【讨论】:

  • 我可以在我使用 @Autowire 的同一个班级中使用这个 @Bean 吗?
  • @Tajinder 是的,我认为这应该没问题 - 您可以轻松尝试并检查它是否有效
【解决方案2】:

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

【讨论】:

  • 而@Autowired on some method 代表什么?
  • @Tajinder 一样。 @Autowired 表示“自动查找实现并通过新创建”
【解决方案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 定义在一个地方而不是注释单个类。我通常根据需要使用两者。

【讨论】:

  • 这不是春天的想法。你永远不应该在你的代码中使用new {ConcreteImplementation}
  • Autowired 在方法上的工作类似于构造函数,但我更喜欢构造函数,因为只有在满足所需的依赖项时才会实例化您的单例 bean。我相信方法注入不太可靠。
  • @dit 这只是一个例子。
猜你喜欢
  • 1970-01-01
  • 2018-12-10
  • 2015-11-17
  • 1970-01-01
  • 2011-04-25
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多