这次我们来介绍spring的另一种自动装配方式byName,首先我们单独的看它应该跟名字有什么直接或者间接的联系。为了例证我们的推断,我们当然要看其定义了。
1. byName:在容器中寻找和需要自动装配的属性名相同的Bean(或ID),如果没有找到相符的Bean,该属性就没有被装配上。
大概就是我们的理解根据属性的名字到xml中寻找相应的bean,那么在具体实现中我们应该怎样去实现总动封装呢
<?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-2.5.xsd"
>
<!--根据id检索-->
<bean id="greetingDaoImpl"
class="cn.csdn.dao.GreetingDaoImpl" scope="singleton">
<property name="say">
<value>Longmanfei</value>
</property>
</bean>
<bean id="greetingServiceImpl"
class="cn.csdn.service.GreetingServiceImpl"
scope="singleton" autowire="byName"/>
</beans>
//GreetingDaoImpl
public class GreetingDaoImpl implements GreetingDao {
private String say;
public void say() {
System.out.println("我打了这个招呼"+say);
}
public void setSay(String say) {
this.say = say;
}
}
//GreetingServiceImpl
public class GreetingServiceImpl implements GreetingService{
private GreetingDaoImpl greetingDaoImpl;//注意属性名称和xml里的id
public void say() {
greetingDaoImpl.say();
}
public void setGreetingDaoImpl(GreetingDaoImpl gdi) {
System.out.println("我调用了set方法");
this.greetingDaoImpl = gdi;
}
public GreetingServiceImpl() {
super();
System.out.println("我调用了空的构造器");
}
public GreetingServiceImpl(GreetingDaoImpl greetingDaoImpl) {
super();
System.out.println("我调用了有参的构造器");
this.greetingDaoImpl = greetingDaoImpl;
}
}
//junit测试
@Test
public void test1(){
/*加载spring容器可以解析多个配置文件采用数组方式传递*/
ApplicationContext
ac=New ClassPathXmlApplicationContext("classpath:LongmanfeibyName.xml");
//直接转换成接口便于日后修改数据/*Ioc控制反转体现*/
GreetingService
gs=(GreetingService) ac.getBean("greetingServiceImpl");
gs.say();
}
<!--EndFragment-->
分享到:
相关推荐
ean的自动装配,有4种 (1)no:不做任何操作 (2)byName:根据属性 名 自动装配,设值注入 <bean id="xxx" class="xxx" ></bean> (3)byType:根据属性 类型 自动装配,相同类型多个会抛出异常,设值注入 ...
本项目为Java项目,使用Spring实现自动装配,根据类型方式实现自动装配。适合初学者了解Spring不同装配方式。
Spring自动装配解析,具体效果和过程看博文 http://blog.csdn.net/evankaka/article/details/44836069
spring自动装配项目struts2,使用了struts2 ,spring2.5 ,hibernate,和spring 自动装配
spring的自动装配
Spring中的自动装配有哪些限制?.docx Spring中的自动装配有哪些限制?.docx Spring中的自动装配有哪些限制?.docx
Spring自动装配的方式和举例、以及@Qualifier、@Autowire、@Resource的使用。
Spring 自动装配及其注解 博客:https://blog.csdn.net/u010476739/article/details/76735241
NULL 博文链接:https://cdxs2.iteye.com/blog/1941095
主要为大家详细介绍了Java注解机制之Spring自动装配实现原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
NULL 博文链接:https://garrincha.iteye.com/blog/2109688
spring-boot自动装配原理.md
Spring如何装配各种集合类型的属性
使用Spring进行装配使用Spring进行装配
spring中的自动装配的形式byType、byName、no、construtor、autodetect和default(beans标签中没有,而bean标签中有该属性)共6种装配的方式的举例说明
我知道大家有些学的自动转配模式不清楚,所以我传了一个自动转配的模式表
Spring实现集合(List_Map_Set)_自动装配,适合初学者熟悉集合类型的装配。
主要介绍了Spring 自动装配的二义性实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
spring中的自动装配实例byName、byType,两种装配方式的实例。有需要学习的朋友可以看一下。
编码剖析Spring装配基本属性的原理