lookup方法注入

/ Spring / 没有评论 / 271浏览

在这篇文章中我们主要介绍spring框架的IOC容器的方法注入功能,也就是lookup。通过lookup我们可以修改对象方法的逻辑及动态为对象方法添加实现的功能。我们请一下下面的测试用例。

public class User {

private String username;
private String password;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
public interface UserFactory {
User createUser();
}
<bean id="user" class="com.jilinwula.spring.User" p:username="admin" p:password="jilinwula"/>
<bean id="userFactory" class="com.jilinwula.spring.UserFactory">
<lookup-method name="createUser" bean="user"/>
</bean>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UserFactory userFactory = applicationContext.getBean("userFactory", UserFactory.class);
System.out.println(userFactory.createUser());
}
User{username='admin', password='jilinwula'}
public class User {

private String username;
private String password;
private Work work;

public Work getWork() {
return work;
}

public void setWork(Work work) {
this.work = work;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}
<bean id="work" class="com.jilinwula.spring.Work" p:address="吉林乌拉"/>
<bean id="work2" class="com.jilinwula.spring.Work" p:address="吉林乌拉2"/>
<bean id="user" class="com.jilinwula.spring.User" p:username="admin" p:password="jilinwula" p:work-ref="work">
<lookup-method name="getWork" bean="work2"/>
</bean>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user.getWork());
}
Work{address='吉林乌拉2'}