spring中bean标签的属性、子元素配置详解 |
您所在的位置:网站首页 › scope属性用于指定Bean的作用域 › spring中bean标签的属性、子元素配置详解 |
spring中有4种默认标签:import,alias,bean,beans;以下是各个标签中属性以及子元素配置的作用和用法。 (本人使用的是spring 4.2,若有错误,烦请指正) bean标签 标签属性 idid是bean的唯一标识符,在spring容器中不可能同时存在两个相同的id; class类的全限定名(包名+类名),用“.”号连接; name别名(alias),用法:getBean("name"),支持设置多个别名,之间用英文逗号分割; abstract设置bean是否为抽象类,默认abstract="false",如果设为true,将不能被实例化; autowire-candidate默认为true,如果为false,那么该bean不能作为其他bean自动装配的候选者。不懂?请看下面的例子: 定义一个UserService,UserServiceImpl继承它: UserService @Service public interface UserService { public void getUser(); }UserServiceImpl public class UserServiceImpl implements UserService{ @Override public void getUser() { System.out.println("获得一个user"); } }在applicationContext.xml设置UserServiceImpl的属性autowire-candidate为false,此时该bean不能作为UserService自动装配的对象。 测试类: @Autowired @Qualifier("service") private UserService service2;此时将会报以下错误:大概意思是没有一个合适的子类能够自动注入到service2中。 Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bcu.service.UserService com.bcu.test.UnitTets.service2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bcu.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=service)}如果将autowire-candidate改为true,此时id="service"的bean实例化后的对象指向service2引用。 autowiredefault(默认):采用父级标签beans中的default-autowire属性; byName:通过属性名称来自动装配,即A类中的B对象名称为name,那么将根据id="name"找到该bean进行装配,A类必须提供setName方法; byType:根据属性类型来找到和配置文件中配置的class类型一致的bean来自动装配,如果找到多个类型一致的bean,则抛异常,如果一个都没有找到,则不执行装配操作,也不抛出异常。 no:不执行自动装配操作,只能用 测试类: ApplicationContext ac = new ClassPathXmlApplicationContext("lookup-test.xml"); GetBeanTest test = (GetBeanTest) ac.getBean("getBeanTest"); test.showMe();测试结果: 首先看配置文件中getBean配置了lookup-method="teacher",它的作用是使得GetBeanTest类中的getBean方法的返回类型指定为id="teacher"的bean类型。然后看一下GetBeanTest的showMe方法,它调用了getBean方法,lookup-method标签会自动重写该方法。 示例: public class ReplacedMethodTest implements MethodReplacer{ @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("我代替了原来的方法"); return null; } }配置文件: lisi编写一个实现MethodReplacer接口,并且重写reimplement方法的类,通过配置文件动态地替换原始方法。 构造器参数(顺序注入),此种方式会按照顺序注入构造器的参数。(以LinkedList形式存于BeanDefinition中) 上海市徐汇区陆家嘴下标注入,按照下标顺序注入构造器参数,(以LinkedHashMap形式存于BeanDefinition中) Jack 上海市徐汇区陆家嘴自动注入jaabean的成员变量: 4.7 5.5 5.8 appStore weChat camera指定注入的bean名称,一般不使用这种方法,而使用注解@Qualifier("bean") |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |