转载

Spring IOC的四种注入方式

1、IOC

1.1、IOC本质

控制反转( Inversion of Control ),是一种设计思想,而依赖注入( DI )是一种实现的方法。原本对象的创建是依靠程序员来创建,通过依赖注入的方法来改造后,对象的创建是依赖IOC容器,对象的属性依赖IOC容器注入。

依赖注入:set注入

依赖:Bean对象的创建依赖容器

注入:Bean对象所有属性由容器注入

1.2、依赖注入的四种形式:

1.2.1、Set方式注入(Setter Injection)[重要]

Setter方法注入是容器通过调用无参构造器或无参static工厂 方法实例化bean之后,调用该bean的setter方法,即实现了基于setter的依赖注入。

package service;

import dao.UserDAO;

public class UserServiceImpl {
    private UserDAO userDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void getUser() {
        userDAO.getUser();
    }
}
package dao;

public class UserDAOImpl implements UserDAO {
    public void getUser() {
        System.out.println("userDAOImpl");
    }
}

XML配Bean代码

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

    <bean id="a" class="dao.UserDAOImpl"/>

    <bean id="hello" class="service.UserServiceImpl" >
        <property name="userDAO" ref="a"/>
    </bean>
 </beans>

测试代码

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl test = context.getBean("hello", UserServiceImpl.class);
        test.getUser();
    }
}

1.2.2、构造器注入(Constructor Injection)

构造器依赖注入通过容器触发一个类的构造器来实现的,该类有一系列参数,每个参数代表一个对其他类的依赖。

XML配Bean代码

<?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="userDaoImpl" class="dao.UserDAOImpl"/>
    <bean id="construct" class="ConstructDi.UserServiceImpl">
        <constructor-arg ref="userDaoImpl"/>
    </bean>
</beans>

测试代码

public class MyConstructTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("constructDiBean.xml");
        UserServiceImpl construct = context.getBean("construct", UserServiceImpl.class);
        construct.getUserDAO().getUser();
    }
}

1.2.3、注解方式

@Autowired默认按类型装配

@Qualifier和Autowired配合使用,指定bean的名称

@Resource默认按名称装配,当找不到与名称匹配的bean时,才会按类型装配。

例子:人有狗和猫,两种宠物通过不同的方式注入。

三个实体类分别为:人、猫、狗

package pojo;

@Component
public class People {
    @Autowired
    @Qualifier("cat")
    Cat cat;
    @Resource
    Dog dog;


    public Cat getCat() {
        return cat;
    }

    public Dog getDog() {
        return dog;
    }

    @Override
    public String toString() {
        return "People{"
                +" cat=" + cat.name +
                ", dog=" + dog.name +
                '}';
    }
}
package pojo;

@Component
public class Cat {
    public String name="catName";

    public void shout(){
        System.out.println("Cat shout!");
    }
    public String getName() {
        return name;
    }

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

import org.springframework.stereotype.Component;

@Component
public class Dog {
    String name="dogName";

    public void shout(){
        System.out.println("Dog shout!");
    }
    public String getName() {
        return name;
    }

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

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: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 https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="pojo"/>
    <context:annotation-config/>
</beans>

测试的代码

public class MyTest {
    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        People people = context.getBean("people", People.class);
        people.getCat().shout();
        people.getDog().shout();
        System.out.println(people.toString());
    }
}

结果:

Cat shout!

Dog shout!

People{ cat=catName, dog=dogName}

1.2.4、接口注入(Interface Injection)[已废弃]

public class ClassA {  
  private InterfaceB clzB;  
  public void doSomething() {  
    Ojbect obj = Class.forName(Config.BImplementation).newInstance();  
    clzB = (InterfaceB)obj;  
    clzB.doIt();   
  }

本人学识有限,如果有错,欢迎指出。

原文  https://segmentfault.com/a/1190000023309818
正文到此结束
Loading...