Spring Bean 注入 2 注解篇

时间:2023-03-09 15:48:08
Spring Bean 注入 2 注解篇

1. 自动装配注解

配置applicationContext.xml开启注解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 注解使用示例 -->
<!-- 开启注解 -->
<context:annotation-config /> </beans>

注解使用示例

    /** Value 注解可以使用SpEL,对基本数据类型完成注入 */
@Value("#{americanA.getName}")
public void setName(String name) {
this.name = name;
} /**
* Autowired表示使用byType自动装配该属性,他除了用在set方法也可以用在其他方法
* required属性表示可以允许找不到匹配的bean,而将该属性置为null
* Qualifier表示制定装配该属性的bean id为"catA"
* */
@Autowired(required = false)
@Qualifier("catA")
public void setPet(Pet pet) {
this.pet = pet;
} /** Inject和Named的使用与Autowired和Qualifier基本相同,只是没有required属性 */
@Inject
@Named("catA")
public void setPet(Pet pet) {
this.pet = pet;
}

2.  自动注册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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启自动检测bean注解 -->
<!-- base-package表示会扫描com.qunar.bean及其所有子包,对使用了自动注册注解的类进行自动注册 -->
<context:component-scan base-package="com.qunar.bean">
<!-- 过滤哪些类需要被注册,type有5种类型 -->
<!-- assignable表示扫描派生与expression指定类型的类 -->
<!-- annotation表示扫描使用了指定注解标注的类 -->
<!-- aspectj表示扫描与expression指定的AspectJ表达式匹配的类 -->
<!-- custom表示使用自定义的TypeFilter实现类 -->
<!-- regex表示过滤雷鸣宇expression指定的正则表达式相匹配的类 -->
<context:include-filter type="assignable"
expression="com.qunar.bean.People" />
<!-- 过滤哪些类不能被注册 -->
<context:exclude-filter type="assignable"
expression="com.qunar.bean.Cat" />
</context:component-scan> </beans>
/**
* @Component 标志该类为Spring组件
* @Controller 标志该类为Spring MVC Controller
* @Repository 标志该类为数据仓库
* @Service 标志该类为服务
*/
@Component("myCat") // 将该类自动注册为bean并将id命名为myCat
public class Cat extends Pet {
public Cat() {
} @Override
public String bark() {
return "miao";
}
}