如何使用Spring 框架实现注入和替换?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
首先配置 XML:
<bean id="author" class="net.deniro.spring4.bean.Author" scope="prototype"/>
<bean id="book" class="net.deniro.spring4.bean.Book"
p:name="面纱">
</bean>
bean author 的 scope 设置为 prototype。
Book 类实现 BeanFactoryAware 接口:
public class Book implements BeanFactoryAware {
...
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory;
}
public Author getPrototypeAuthor() {
return (Author) factory.getBean("author");
}
}
单元测试:
ApplicationContext context;
@BeforeMethod
public void setUp() throws Exception {
context = new ClassPathXmlApplicationContext("beans5-5.xml");
}
@Test
public void test(){
Book book= (Book) context.getBean("book");
System.out.println(book.getAuthor().hashCode());
System.out.println(book.getAuthor().hashCode());
System.out.println(book.getPrototypeAuthor().hashCode());
System.out.println(book.getPrototypeAuthor().hashCode());
测试结果
从结果中可以发现,只有从 BeanFactory 中获取得到的 Author 实例是不同的。
这种实现把应用与 Spring 框架绑定在了一起,是否有更好的解决方案呢?有,就是注入方法。
1 注入方法
Spring 容器依赖于 CGLib 库,所以可以在运行期动态操作 Class 的字节码,比如动态地创建 Bean 的子类或实现类。
BookInterface 接口:
public interface BookInterface {
Author getAuthor();
}
XML 配置:
<!-- 方法注入-->
<bean id="author" class="net.deniro.spring4.bean.Author" scope="prototype"
p:name="毛姆"
/>
<bean id="book2" class="net.deniro.spring4.bean.BookInterface">
<lookup-method name="getAuthor" bean="author"/>
</bean>
单元测试:
BookInterface book= (BookInterface) context.getBean("book2");
Assert.assertEquals("毛姆",book.getAuthor().getName());
Assert.assertTrue(book.getAuthor().hashCode()!=book.getAuthor().hashCode());
通过这种配置方式,就可以为接口提供动态实现啦,而且这样返回的 Bean 都是新的实例。
所以,如果希望在一个 singleton Bean 中获取一个 prototype Bean 时,就可以使用 lookup 来实现注入方法。
2 替换方法
在 Spring 中,可以使用某个 Bean 的方法去替换另一个 Bean 的方法。
假设 Book 中有一个 getName() 方法,用于获取书名:
/**
* 书名
*/
private String name;
public String getName() {
return name;
}
我们现在新建一个 Bean,它实现了 MethodReplacer 接口,用于替换 Book 中的 getName() 方法:
public class Book4 implements MethodReplacer {
@Override
public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
return "活着";
}
}
配置:
<bean id="book3" class="net.deniro.spring4.bean.Book"
p:name="灿烂千阳">
<replaced-method name="getName" replacer="book4"/>
</bean>
<bean id="book4" class="net.deniro.spring4.bean.Book4"/>
测试:
Book book= (Book) context.getBean("book3");
assertEquals("活着", book.getName());
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。