标签:spring
一:常用模式
二:案例byName
1.案例截图
2.基本代码
package com.cloud.autowire;
public classDog {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.cloud.autowire;
public classMaster {
private String name;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
returndog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
3.配置代码
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置一个Master对象 -->
<!-- autowire="byName"配置自动装配属性 -->
<!-- 原理:在Master里面有一个dog属性没有配置, 使用byName之后就会在下面配置的属性里面寻找dog属性,
一旦找到就会自动装配-->
<bean id="master" class="com.cloud.auto.Master" autowire="byName">
<property name="name">
<value>Spring</value>
</property>
</bean>
<!-- 配置一个Dog对象 -->
<bean id="dog" class="com.cloud.auto.Dog">
<property name="name" value="小白"/>
<property name="age" value="10"/>
</bean>
</beans>
4.测试代码
package com.cloud.auto;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("com/cloud/auto/beans.xml");
Master master=(Master) ac.getBean("master");
System.out.println(master.getName()+"养的狗叫:"+master.getDog().getName());
}
}
版权声明:博主原创文章,转载请说明出处。http://blog.csdn.net/dzy21
标签:spring
原文地址:http://blog.csdn.net/dzy21/article/details/48085981