DI依赖注入方式
构造器注入:
前面一个博客说了
Set方法注入【重点】:
复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String ,String > card;
private Set<String > games;
private String wife;
private Properties info;
}
beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--第一种,普通值注入,直接使用value-->
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="陈东"/>
</bean>
</beans>
测试类
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="连云港"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!--第一种,普通值注入,直接使用value-->
<property name="name" value="陈东"/>
<!--第二种,bean注入,ref-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>红楼</value>
<value>西游</value>
<value>水浒</value>
<value>三国</value>
</array>
</property>
<!--List-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="建设" value="1456682255511"/>
<entry key="中国邮政" value="456456456465456"/>
</map>
</property>
<!--Set-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!--Null-->
<property name="wife">
<null></null>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="学号">123456789</prop>
<prop key="性别">男</prop>
<prop key="姓名">小红</prop>
</props>
</property>
</bean>
拓展方式注入:
p命名空间,c命名空间
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性值:proerties -->
<bean id="user" class="com.kuang.pojo.User" p:age="18" p:name="陈"/>
<!--c命名空间注入,通过构造器注入:Construct-org -->
<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="陈东"/>
</beans>
需要导入对应的xml约束
bean的作用域:
单例模式:(spring的默认机制)
原型模式:每次从容器种get都会创建一个新的对象
其余几个都是在web开发中使用