关于spring:Spring字段注入

39次阅读

共计 2012 个字符,预计需要花费 6 分钟才能阅读完成。

实现办法 / 手动模式

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

}

输入

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

正文完
 0