如果没有autowire的另一个配置,如何将一个bean的属性设置为另一个bean?

时间:2015-10-19 10:08:09

标签: java spring dependency-injection

@Autowire的帮助下,可以在另一个配置中设置bean的属性。

是否可以在基于Java的配置代码中进行等效分配?

样本如下。

输出:

instance1.instance2 = com.inthemoon.snippets.springframework.InterconfigSettingTry$Bean2@574b560f
instance1.instance3 = null

证明,该属性在配置之间自动装配。

示例包含注释,解释,我想分配属性而不是@Autowired

public class InterconfigSettingTry {


   // first bean class with two properties, one of which is set with autowire, while another does not
   public static class Bean1 {

      @Autowired
      public Bean2 instance2;

      // @Autowired // not using autowire feature
      public Bean2 instance3;

   }

   // second bean class, which will be instantiated in two beans
   public static class Bean2 {
   }

   // java based configuration #1, which contains a bean, wishing to be aware of two beans in another config
   @Configuration
   public static class _Config1 {

      @Bean
      public Bean1 instance1() {

         Bean1 ans = new Bean1();

         // how to set ans.instance3 here without autowire?
         //ans.instance3 = ???

         return ans;
      }


   }

   // java based configuration #2
   @Configuration
   public static class _Config2 {
      @Bean
      public Bean2 instance2() {
         return new Bean2();
      }

      @Bean
      public Bean2 instance3() {
         return new Bean2();
      }
   }

   // main method 
   public static void main(String[] args) {

      ApplicationContext context = new AnnotationConfigApplicationContext(_Config1.class, _Config2.class);

      Bean1 instance1 = (Bean1) context.getBean("instance1");

      System.out.println("instance1.instance2 = " + instance1.instance2);
      System.out.println("instance1.instance3 = " + instance1.instance3);

   }

}

0 个答案:

没有答案