脚本宝典收集整理的这篇文章主要介绍了依赖注入、Bean的自动装配等,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
之前写的
依赖注入:Set注入!
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入!
【环境搭建】
复杂类型
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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="student" class="com.kuang.pojo.Student"><!-- 第一种,普通值注入,value--> <property name="name" value="荣哥"></property> </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="南昌"></property> </bean> <bean id="student" class="com.kuang.pojo.Student"><!-- 第一种,普通值注入,value--> <property name="name" value="荣哥"></property><!-- 第二种,Bean注入,ref--> <property name="address" ref="address"></property><!-- 数组--> <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="12121242"></entry> <entry key="银行卡" value="124253434"></entry> </map> </property><!-- Set--> <property name="games"> <set> <value>LOL</value> <value>COC</value> </set> </property><!-- null--> <property name="wife"> <null/> </property><!-- Properties--> <property name="info">