依赖注入
1.构造器注入
2.set注入
- 依赖注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,有容器来注入
环境搭建
复杂类型
public class Address { private String address; // getter, setter, toString }
真实对象
public class Student { private String name; private Address address; private String[] books; private List<String> hobbies; private Map<String,String> card; private Set<String> games; private String girlfriend; private Properties info; // getter, setter, toString }
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"> <bean id="address" class="cn.pinked.pojo.Address"> <property name="address" value="earth"/> </bean> <bean id="student" class="cn.pinked.pojo.Student"> <property name="name" value="大头儿子"/> <property name="address" ref="address"/> <property name="books"> <array> <value>西游记</value> <value>三国演义</value> <value>水浒传</value> <value>红楼梦</value> </array> </property> <property name="hobbies"> <list> <value>唱</value> <value>跳</value> <value>rap</value> <value>篮球</value> </list> </property> <property name="card"> <map> <entry key="studentcard" value="12345678"/> <entry key="raedercard" value="12345678"/> </map> </property> <property name="games"> <set> <value>dead game</value> </set> </property> <property name="girlfriend"> <null/> </property> <property name="info"> <props> <prop key="身高">150cm</prop> <prop key="体重">50kg</prop> </props> </property> </bean> </beans>
测试类
@Test public void Student(){ ApplicationContext context = new ClasspathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); }
3.扩展方式注入
可以使用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">
<bean id="user" class="cn.pinked.pojo.User" p:name="大头儿子" p:age="6"/>
<bean id="user2" class="cn.pinked.pojo.User" c:name="小头爸爸" c:age="37"/>
</beans>
- p命名空间和c命名空间不能直接使用,需要导入xml约束
- c命名空间需要有参构造器
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。