Spring注入方式

2020-06-14  本文已影响0人  河神

1. Set注入

    <bean name="notebook1" class="com.spring.injection.domin.Notebook" primary="true">
        <property name="cpu" value="因特尔" />
        <property name="disk" value="2048" />
        <property name="memory" value="1024" />
    </bean>
        @Bean
        public Bag bag2(){
            Bag bag = new Bag();
            bag.setNotebook(notebook2);
            return bag;
        }

2. 构造器注入

    <bean name="notebook2" class="com.spring.injection.domin.Notebook" >
        <constructor-arg value="联发科" />
        <constructor-arg value="2048" />
        <constructor-arg value="1024" />
    </bean>
        @Bean
        public Bag bag(){
            return new Bag(notebook1);
        }

3. BeanDefinition注入

        AnnotationConfigApplicationContext applicationContext = 
                  new AnnotationConfigApplicationContext();

        XmlBeanDefinitionReader xmlBeanDefinitionReader = 
                  new XmlBeanDefinitionReader(applicationContext);
        xmlBeanDefinitionReader.loadBeanDefinitions("classpath:meta-data/injection-bean.xml");

        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Bag.class);
        definitionBuilder.addPropertyReference("notebook","notebook1");
        definitionBuilder.setScope(BeanDefinition.SCOPE_SINGLETON);
        String benName = BeanDefinitionReaderUtils.generateBeanName(definitionBuilder.getBeanDefinition(),applicationContext);
        applicationContext.registerBeanDefinition(benName,definitionBuilder.getBeanDefinition());


        BeanDefinitionBuilder definitionBuilder2 = BeanDefinitionBuilder.genericBeanDefinition(Bag.class);
        definitionBuilder2.addConstructorArgReference("notebook2");
        definitionBuilder2.setScope(BeanDefinition.SCOPE_SINGLETON);
        String benName2 = BeanDefinitionReaderUtils.generateBeanName(definitionBuilder2.getBeanDefinition(),applicationContext);

  applicationContext.registerBeanDefinition(benName2,definitionBuilder2.getBeanDefinition());


        applicationContext.refresh();
        Map<String, Bag> beansOfType = applicationContext.getBeansOfType(Bag.class);
        System.out.println(beansOfType);

4. 回调接口 Aware 注入

@Data
public class PostUser implements   BeanNameAware {

    private int id;
    private String name;
    private String beanName;

    public PostUser() {
        id = 1;
        name = "init";
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("setBeanName: "+ name);
        this.beanName = name;
    }
}

5. 外部配置注入

   @Value("${name:look}")
   private String name;

6.字段注入 (使用 @Autowired @Resource @Inject注入)

参数 默认 指定name 作用域
@Autowired 默认根据类型注入 @Qualifier,@Named(测试有效) 变量、setter方法、构造函数
@Resource 默认根据name注入 - 变量、setter方法
@Inject 默认根据类型注入 @Named,@Qualifier(测试有效) 变量、setter方法、构造函数
上一篇下一篇

猜你喜欢

热点阅读