spring 属性注入

1、创建对象时,向类属性里面设置值
2、java属性注入的三种方式
  • set方法


    spring 属性注入_第1张图片
    image.png
  • 有参构造


    spring 属性注入_第2张图片
    image.png
  • 接口注入


    spring 属性注入_第3张图片
    image.png
3、在spring中只支持两种方式
(1)set方法注入

PropertyUser.java

package work.zhangdoudou.Property;

public class PropertyUser {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }   
}

applicationContext.xml



    
    
        
        
    

测试类TestPropertyUser.java

package work.zhangdoudou.test;

import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import work.zhangdoudou.Property.PropertyUser;

public class TestPropertyUser {

    @Test
    public void test() {
        //1加载配置文件,根据创建对象
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //2得到创建的对象
        PropertyUser propertyUser=(PropertyUser) context.getBean("propertyUser");
        System.out.println(propertyUser.getUsername());
    }

}

运行结果


spring 属性注入_第4张图片
image.png
(2)有参数构造注入

PropertyUser1.java

package work.zhangdoudou.Property;

public class PropertyUser1 {
    private String username;

    public PropertyUser1(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }   
}

applicationContext.xml


 
    
    
        
        
    

测试类TestPropertyUser1.java

package work.zhangdoudou.test;

import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import work.zhangdoudou.Property.PropertyUser1;

public class TestPropertyUser1 {

    @Test
    public void test() {
        //1加载配置文件,根据创建对象
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //2得到创建的对象
        PropertyUser1 propertyUser1=(PropertyUser1) context.getBean("propertyUser1");
        System.out.println(propertyUser1.getUsername());
    }

}

运行结果


spring 属性注入_第5张图片
image.png

你可能感兴趣的:(spring 属性注入)