spring-装配

Spring装配有三种方式: 基于XML的显式配置 基于注解的自动装配 在java中进行显示配置 1、基于注解的自动装配 Spring从组件扫描和自动装配两个角度实现自动转配 组件扫描:Spring会自动发现应用上下文中所创建的bean,配置时需要指定扫描的包 复制代码 复制代码 组件扫描会将标记了以下注解的类实例化交给Spring容器管理 复制代码 @Controller、@Service、@Repository、@Component 复制代码 自动装配:Spring自动满足bean之间的依赖   在组件扫描时候,创建bean之后,容器会尽可能的去满足bean的依赖。自动装配通过注解@Autowired实现,该注解定义如下: 复制代码 @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autowired { boolean required() default true; } 复制代码 a、属性required的值默认为true,表明在创建bean后,一定要被@Autowired注解的类型装配上匹配的bean,否则,容器启动会抛出异常: 复制代码 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cn.pojo.Person] 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)} 复制代码 b、将required的值设置为false,spring会尝试执行自动装配,但如果没有匹配的bean,spring会让这个bean处于未装配状态。这时,会有隐患,通常需要进行null检查,否则抛出NullPointerException异常 c、无论是否设置required的值,当容器中存在有多个bean满足依赖关系,spring将会抛出一个异常,表明没有明确指出要选择哪个bean进行自动装配。 Spring提供了多种可选方案解决这样的歧义: 1)将可选bean中的某一个设为首选,当装配遇到这样的歧义时候,spring将会使用首选bean。 @Primary注解配置,常与@Controller、@Service、@Repository、@Component使用: 复制代码 package com.cn.pojo; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Primary @Component public class Person {   //... } 复制代码 或者xml配置: 复制代码 复制代码 注:如果配置了两个或者两个以上的首选bean,那么它就无法正常工作了,同样还是有歧义。 2)使用限定符指定spring装配的bean @Qualifier注解是使用限定符的主要方式,常与@Autowired使用 复制代码 package com.cn.controller; import com.cn.pojo.Person1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; @Controller public class HelloController { @Autowired @Qualifier("person1") private Person1 person1; public void print(){ System.out.println(person1.toString()); } } 复制代码 限定符:   实例化一个bean时候,默认限定符为首字母小写的类名。与默认的bean的ID规则一致,如果bean不想使用默认id,可以在@Controller、@Service、@Repository、@Component上指定id的值。 可以在实例化对象时候,使用 @Qualifier注解指定类的限定符 复制代码 package com.cn.pojo; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component @Qualifier("person100") public class Person1 { //... } 复制代码 2、基于XML的显式配置 使用构造器初始化bean a、装配字面量 b、装配bean c、装配集合 d、c命名空间 设置属性初始化bean a、装配字面量 b、装配bean c、装配集合 d、p命名空间 util命名空间:用于定义独立于bean之外的集合,可被引用装配bean 小结:通常项目中将基于注解的自动装配和基于XML的显示配置结合使用,在java中进行显示配置用的不多。https://www.cnblogs.com/shixiemayi/p/9545279.html
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信