DI(Dependency Injection)是AOP中一个重要的概念,作用是给Spring容器管理的对象进行属性值的注入。
注入有三种实现方式:
(1)带参构造方法注入
(2)参数对应setter方法注入
(3)参数直接注入(修改访问权限)
1,2是利用配置xml文件进行注入的主要实现方式,3是利用配置注解进行注入的主要实现方式。
注意:
(1)如果注入的属性是一个对象,那么还可以配置xml文件或者注解实现对象属性的自动注入。
(2)本文只说明DI的配置方式,不涉及其应用环境。
(3)本文中让Spring托管的bean都是程序员自定义的类对象,要想让Spring托管官方的类对象,请关注后续博客。
带参构造方法注入
ApplicationContext.xml
<bean name="student" class="domain.Student" scope="singleton" lazy-init="false">
<constructor-arg name="name" value="john"></constructor-arg>
<constructor-arg name="age" value="12"></constructor-arg>
<constructor-arg name="sex" value="male"></constructor-arg>
</bean>
参数对应setter方法注入
ApplicationContext.xml
<bean name="student" class="domain.Student" scope="singleton" lazy-init="false">
<property name="name" value="john"></property>
<property name="age" value="12"></property>
<property name="sex" value="male"></property>
</bean>
参数直接注入
ApplicationContext.xml
<context:component-scan base-package="domain"></context:component-scan>
Student.java
@Component("student")
@Scope("singleton")
@Lazy(false)
public class Student {
@Value("john")
private String name;
@Value("12")
private int age;
@Value("male")
private String sex;
public Student() {}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
}