您的位置:首页 > 编程语言 > Java开发

spring方法注入

2015-09-17 15:32 453 查看
Spring bean
作用域默认是 单例
singleton; 可以通过配置
prototype ,实现多例


<span style="white-space:pre">	</span><bean id="dog" class="com.java1234.entity.Dog">
<property name="name" value="Jack"></property>
</bean>

(ture)System.out.println(ac.getBean("dog")==ac.getBean("dog"));
<span style="font-family: SimSun;">	</span><span style="font-family: SimSun;"><bean id="dog" class="com.java1234.entity.Dog"<span style="color:#ff0000;"> scope="prototype"</span>></span>
<property name="name" value="Jack"></property>
</bean>

(false)System.out.println(ac.getBean("dog")==ac.getBean("dog"));   

方法注入
lookup-method

public abstract class People {

private int id;
private String name;
private int age;
private Dog dog;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public abstract Dog getDog();

public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age
+ ", dog=" + dog.getName() + "]";
}

}
public class Dog {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

<?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="dog" class="com.java1234.entity.Dog" scope="prototype">
<property name="name" value="Jack"></property>
</bean>

<bean id="people1" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<span style="color:#ff6666;"><lookup-method name="getDog" bean="dog"/></span>
</bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: