转载

Spring字段注入

实现方法/手动模式

  • Java 注解配置元信息

    • @Autowired 只按照byType 注入,由Spring提供
    • @Resource @Resource默认按byName自动注入,也提供按照byType 注入
    • @Inject(可选)

@Autowired 只按照byType 注入,由Spring提供

@Resource 默认按byName自动注入,也提供按照byType 注入,由JDK提供

// @Inject 需要依赖

<dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
</dependency>

实体类Holder.java

package com.rumenz;

public class Holder {

    private Rumenz rumenz;

    public Holder(Rumenz rumenz) {
        this.rumenz = rumenz;
    }

    public Rumenz getRumenz() {
        return rumenz;
    }

    public void setRumenz(Rumenz rumenz) {
        this.rumenz = rumenz;
    }
}

实体类Rumenz.java

package com.rumenz;

public class Rumenz {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

配置文件Beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="rumenz" class="com.rumenz.Rumenz">
        <property name="id" value="123"/>
        <property name="name" value="入门小站"/>
    </bean>
</beans>

调用

package com.rumenz;

public class DemoApplication {

    @Autowired
    private Holder holder;

    @Resource
    private Holder holder1;


    @Inject
    private Holder holder2;


    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();

        XmlBeanDefinitionReader xr=new XmlBeanDefinitionReader(ac);
        xr.loadBeanDefinitions("Beans.xml");

        ac.register(DemoApplication.class);
        ac.refresh();
        DemoApplication bean = ac.getBean(DemoApplication.class);
        System.out.println(bean.holder.getRumenz().getName());
        System.out.println(bean.holder1.getRumenz().getName());
        System.out.println(bean.holder2.getRumenz().getName());
        ac.close();
    }

    @Bean
    public Holder holder(Rumenz rumenz){
        return new Holder(rumenz);
    }

}

输出

入门小站
入门小站
入门小站

Spring字段注入

原文  https://segmentfault.com/a/1190000023280666
正文到此结束
Loading...