DI依赖注入的方式

依赖注入最常用的两种方式:属性注入和构造器注入

1.基于属性的setXXX方法的依赖注入

User.java

package demo03;

public class User {
    private String username;
    private Integer age;


    public String getUsername() {
        return username;
    }

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

    public Integer getAge() {
        return age;
    }

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

bean03.xml





    
        
        
        
        
    

TestDemo03.java

 public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo03/bean03.xml");
        User user = (User)context.getBean("user");
        System.out.println(user.getUsername()+"---"+user.getAge());
    }

Bean标签的基本属性:
id属性:用于指定Bean的名称
name属性:指定Bean的别名
class属性:用于指定Bean的来源

2.基于构造器的注入

User.java

package demo04;

public class User {
    private String username;
    private Integer age;

    public User(String username, Integer age) {
        this.username = username;
        this.age = age;
    }

    public void print(){
        System.out.println(username+"--"+age);
    }
}

bean04.xml
两种方式:一种是按照参数的类型 type 进行匹配;另一种是按照参数的索引 index 进行匹配





    
        
        
        

        
        
        
    


TestDemo04.java

public class TestDemo04 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo04/bean04.xml");
        User user = (User)context.getBean("user");
        user.print();
    }
}

你可能感兴趣的:(DI依赖注入的方式)