【SSM】Spring的属性注入

目录

一、XML方式

1、构造方法注入

2.属性setter方法注入 

3、复杂类型的属性注入

二、注解方式


一、XML方式

 对于类成员变量,Spring注入方式有三种1.构造方法注入2.属性setter方法注入

1、构造方法注入

通过构造方法注入Bean的属性值或依赖对象,它保证了Bean实例在实例化后就可以使用

 首先创建一个对象类

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在配置文件中添加该类(需使用constructor-arg标签)

<bean id="user" class="com.xyz.beanDemo.User">
        <constructor-arg name="name" value="张三"/>
        <constructor-arg name="age" value="23"/>
</bean>

测试

    @Test
    public void demo1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext
                               ("applicationContext.xml");
        User user = (User) applicationContext.getBean("user");
        user.toString();
    }

2.属性setter方法注入 

使用set方法注入,是在Spring配置文件中,通过<property>设置注入的

 首先创建一个对象类

public class person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在配置文件中添加该类(需使用<property>)

<bean id="person" class="com.xyz.beanDemo.person">
        <property name="name" value="李四"/>
        <property name="age" value="32"/>
</bean>

测试

    @Test
    public void demo2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext
                ("applicationContext.xml");
        person p = (person) applicationContext.getBean("person");
        p.toString();
    }

上面一直使用的是java内置的类型,如果在对象类中引用了其他类,该如何配置?

    此时新添加了一个类Cat

public class Cat {
    private String name;
}

    在person类里引用Cat类

public class person {
    private String name;
    private int age;
    private Cat cat;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", cat=" + cat +
                '}';
    }
}

       这时配置文件如下,因为在cat是引用下面的<bean/>所以需要ref

 <bean id="person" class="com.xyz.beanDemo.person">
        <property name="name" value="李四"/>
        <property name="age" value="32"/>
        <property name="cat" ref="cat"/>
    </bean>

    <bean id="cat" class="com.xyz.beanDemo.Cat">
        <property name="name" value="ketty"/>
</bean>

      测试

    @Test
    public void demo2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext
                ("applicationContext.xml");
        person p = (person) applicationContext.getBean("person");
        p.toString();
    }

3、复杂类型的属性注入

  创建对象

public class CollectionBean {
    private String[] arr;
    private List<String> list;
    private Set<String> set;
    private Map<String,Integer> map;
    private Properties properties;

    @Override
    public String toString() {
        return "CollectionBean{" +
                "arr=" + Arrays.toString(arr) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                ", properties=" + properties +
                '}';
    }

    public String[] getArr() {
        return arr;
    }

    public void setArr(String[] arr) {
        this.arr = arr;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public Map<String, Integer> getMap() {
        return map;
    }

    public void setMap(Map<String, Integer> map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}

  在配置文件中添加

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        复杂类型的属性注入
    -->
    <bean id="collectionBean" class="com.xyz.beanDemo5.CollectionBean">
        <!--数组类型-->
        <property name="arr">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>

        <!--List集合类型-->
        <property name="list">
            <list>
                <value>111</value>
                <value>222</value>
                <value>333</value>
            </list>
        </property>

        <!--Set集合类型-->
        <property name="set">
            <set>
                <value>ddd</value>
                <value>eee</value>
                <value>fff</value>
            </set>
        </property>

        <!--Map集合类型-->
        <property name="map">
            <map>
                <entry key="aaa" value="111"/>
                <entry key="bbb" value="222"/>
                <entry key="ccc" value="333"/>
            </map>
        </property>

        <!--properties类型-->
        <property name="properties">
            <props>
                <prop key="username">root</prop>
                <prop key="userpass">root</prop>
            </props>
        </property>
    </bean>
</beans>

 测试
 

    @Test
    public void demo(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean collection = (CollectionBean) applicationContext.getBean("collectionBean");
        System.out.println(collection);
    }

 

二、注解方式

1.注入普通类型

 首先创建对象类,在该类上添加@Service("userService")注解,该注解括号内容类似于XML方式中Bean标签的id,然后在需要注入的属性的set方法上添加@Value标签,如果没有set方法则直接将注解添加到属性上。

@Service("userService")
public class UserService {

    String food = null;

    public String getFood() {
        return food;
    }

    @Value("food")
    public void setFood(String food) {
        this.food = food;
    }

    public void eat(){
        System.out.println("eat:"+food);
    }
}

 在配置文件中需扫描该包 

<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描指定的包-->
    <context:component-scan base-package="com.xyz.bean"/>

</beans>

测试 

    @Test
    public void demo(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        //属性注入
        userService.food = "米饭";
        userService.eat();
    }

2.注入引用类型(@Autowired和@Resource)

   在开发中Service层需要调用Dao层,如下定义了一个UserDao类,那么如何向Service层注入该类呢?

@Repository("userDao")
public class UserDao {

    public void save(){
        System.out.println("Dao保存用户");
    }
}

       这时就需要使用@Autowired注解进行自动注入, @Autowired默认按照类型进行注入,如果存在两个相同Bean类型相同,则按照名称注入,这时就需要在@Autowired注解下再添加@Qualifier("Bean名称")指定注入Bean的名称.

@Service("userService")
public class UserService {
    
    @AutoWired
    private UserDao userDao;

    public void save(){
        System.out.println("Service的保存用户方法");
        userDao.save();
    }
}

   测试 

    @Test
    public void demo(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.save();
    }

      Spring还提供了@Resource注解,使用该注解必须提供需要注入对象的Bean名称,如:@Resource(name="userDao),

可以看出它等同于@Aotuwired加上@Qualifier

      始终记得要进行注入时,需先保证要进行注入的对象类使用了@Component等注解进行了标识才可以使用。

      以上的注入都是我们自己定义的Java类,如果要使用某些Jar包里的Java类则需要在XML里进行配置<Bean>才可以进行注解注入。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值