Spring字段注入

實現方法/手動模式

  • Java 註解配置元信息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.javaspring

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.javathis

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.xmlspa

<?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>

調用code

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);
    }

}

輸出xml

入門小站
入門小站
入門小站

WechatIMG8.png

相關文章
相關標籤/搜索