简体   繁体   English

当使用自动接线时,将是示例的受益者

[英]When autowiring use would be beneficiary with example

I have recently learned concept of autowiring in spring. 我最近了解了春季自动装配的概念。 When I was trying to understand in which particular scenarios spring autowiring can be useful I came up with the below two reasons from one of the questions asked in our stakoverflow forum. 当我试图了解在哪些特定情况下弹簧自动接线可能有用时,我从stakoverflow论坛中提出的问题之一中提出了以下两个原因。

1.I wanted to read values from a property file and inject them into a bean. 1.我想从属性文件中读取值并将它们注入到bean中。 Only way I could figure out how to do this at start up of my app was to wire the bean in XML (and inject the properties.) I ended up using the "byName" attribute (because the bean was also marked as @Component ) and then used @Autowired @Qualifier("nameIChose") when injecting the bean into another class. 我可以弄清楚如何在应用程序启动时执行此操作的唯一方法是以XML形式连接bean(并注入属性。)我最终使用了“ byName”属性(因为bean也被标记为@Component )然后在将bean注入另一个类时使用@Autowired @Qualifier("nameIChose") It's the only bean I've written that I wire with XML. 这是我编写的唯一使用XML连接的bean。

2.I've found autowiring useful in cases where I've had a factory bean making another bean (whose implementation class name was described in a system property,so I couldn't define the all wiring in XML). 2,我发现自动装配在有工厂Bean制造另一个Bean的情况下很有用(其实现类名称在system属性中描述,因此我无法在XML中定义所有接线)。 I usually prefer to make my wiring explicit though; 通常,我通常更倾向于明确布线。

Can any body please give me some code snippet example of the above situations that would make my understanding of autowiring more clearer? 任何机构都可以给我一些上述情况的代码片段示例,以使我对自动布线的理解更加清楚吗?

Here is an example of injecting properties into a bean. 这是将属性注入bean的示例。

Using field injection: 使用场注入:

@Component
public class YourBean {

    @Value("${your.property.name}")
    private String yourProperty;
}

Using constructor injection: 使用构造函数注入:

@Component
public class YourBean2 {

    private String yourProperty;

    @Autowired
    public YourBeans2(@Value("${your.property.name}") String yourProperty) {
       this.yourProperty = yourProperty;
    }
}

The following is a super simple example of autowiring various beans 以下是自动装配各种bean的超级简单示例

@Component
public class Foo {

    public void doSomething() {

    }
}

@Component
public class Bar {

   private Foo foo;

   @Autowired
   public Bar(Foo foo) {
      this.foo = foo;
   }

   public void doSomethingElse() {
      foo.doSomething();
   }
}

In the previous example, no XML configuration of Foo and Bar needs to be done, Spring automatically picks up the beans because of their @Component annotation (assuming of course that component scanning has been enabled) 在前面的示例中,不需要对Foo和Bar进行XML配置,Spring会由于它们的@Component注释而自动拾取bean(当然,假设已启用了组件扫描)

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

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