replaced方法替换

/ Spring / 没有评论 / 318浏览

在上一篇中我们介绍了lookup的功能,并演示了它的两种方法注入的方式,也就是修改对象方法逻辑和动态为对象方法添加实现类的功能。其中修改对象方法逻辑我们也可以用其它的方法解决,也就是采用replaced的方式实现。我们看下面的测试用例。

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 class UserFactory {
public User getUser() {
User user = new User();
user.setUsername("admin");
user.setPassword("吉林乌拉");
return user;
}
}
public class UserFactory2 implements MethodReplacer {
public Object reimplement(Object o, Method method, Object[] objects) throws Throwable {
User user = new User();
user.setUsername("guest");
user.setPassword("jilinwula");
return user;
}
}
<bean id="userFactory" class="com.jilinwula.spring.UserFactory">
<replaced-method name="getUser" replacer="userFactory2"/>
</bean>
<bean id="userFactory2" class="com.jilinwula.spring.UserFactory2"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UserFactory userFactory = applicationContext.getBean("userFactory", UserFactory.class);
System.out.println(userFactory.getUser());
}
User{username='guest', password='jilinwula'}