spring支持的属性注入的方法有两种set方法、有参数的构造方法。还有一种是使用接口注入,不被spring框架支持。我就是前两种,后一种一带而过。
1.set方法注入,创建一个类。
public class Book {
private String bookname;
// set方法
public void setBookname(String bookname) {
this.bookname = bookname;
}
public void demobook() {
System.out.println("book----" + bookname);
}
}
配置xml文件中的bean管理
<!-- 使用set方法注入属性值 -->
<bean id="book" class="cn.itcast.property.Book">
<!-- 注入属性的值 name 属性值 类里面定义的属性名称 value属性;设置具体的值 -->
<property name="bookname" value="红楼梦"></property>
</bean>
测试方法
@Test
public void testBook() {
// 加载spring配置文件,根据创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 得到配置创建对象
Book book = (Book) context.getBean("book");
book.demobook();
}
运行就出现你想要的结果了。
2.有参数构造注入
public class PropertyDemo1 {
private String username;
public PropertyDemo1(String username) {
this.username = username;
}
public void test1() {
System.out.println("demo1....." + username);
}
}
配置xml文件
<!-- 用有参数构造注入属性 -->
<bean id="demo" class="cn.itcast.property.PropertyDemo1">
<!-- 使用有参构造注入 -->
<constructor-arg name="username" value="小王小马"></constructor-arg>
</bean>
测试方法
@Test
public void testProperty() {
// 加载spring配置文件,根据创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 得到配置创建对象
PropertyDemo1 demo1 = (PropertyDemo1) context.getBean("demo");
demo1.test1();
}
注入复杂类型,数组、list集合、map类型、properties类型
创建类
public class Person {
public String pname;
private String[] arrs;
private List<String> list;
private Map<String, String> map;
private Properties properties;
public void setArrs(String[] arrs) {
this.arrs = arrs;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setPname(String pname) {
this.pname = pname;
}
public void test1() {
System.out.println("arrs:" + arrs);
System.out.println("list:" + list);
System.out.println("map:" + map);
System.out.println("properties:" + properties);
}
}
xml配置文件
<!-- 注入复杂类型属性值 -->
<bean id="person" class="cn.itcast.property.Person">
<!-- 数组 -->
<property name="arrs">
<list>
<value>小马</value>
<value>小网</value>
<value>小曝</value>
</list>
</property>
<!-- list -->
<property name="list">
<list>
<value>小马</value>
<value>小网</value>
<value>小曝</value>
</list>
</property>
<!-- map -->
<property name="map">
<map>
<entry key="aa" value="lucy"></entry>
<entry key="bb" value="mary"></entry>
<entry key="cc" value="tom"></entry>
</map>
</property>
<!-- properties -->
<property name="properties">
<props>
<prop key="driverclass">com.mysql.jdbc.Driver</prop>
<prop key="username">root</prop>
</props>
</property>
</bean>
测试方法
@Test
public void testPerson() {
// 加载spring配置文件,根据创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 得到配置创建对象
Person person = (Person) context.getBean("person");
person.test1();
}