Bean管理——基于注解方式
1)——什么是注解
1.1)——注解是代码的特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值...)
1.2)——注解可以作用在 类,方法,属性上
1.3) ——使用注解的目的:为了简化xml配置
2)——Spring针对Bean管理中创建对象提供的注解
2.1)——@Component
2.2)——@Service:一般用在业务逻辑层上
2.3)——@Controller:一般用在web层上
2.4)——@Repository:一般用在dao层
四个注解都可以创建实例对象,
3)——基于注解实现对象创建
3.1)——引入spring-aop的RELEASE的jar包
3.2)——开启组件扫描
3.2.1)——如果扫描多个包,多个包使用逗号隔开
3.2.2)——扫描包的上层目录
<context:component-scan base-package="com.基于注解"></context:component-scan>
3.3)——创建类,在类上面添加创建对象注解
@Component(value = "userService")
//注解里面的value属性值可以不写,默认值是首字母小写的类名
4)——组件扫描配置
<!-- 实例1:扫描在sb包中带有Component注解的类
use-default-filters="false",表示现在不使用默认filter,自己配置filter
use-default-filters 属性的默认值为 true,即使用默认的 Filter 进行包扫描,
而默认的 Filter 对标有 @Service,@Controller和@Repository 的注解的类进行扫描
context:include-filter,设置扫描那些内容
annotation:根据注解来扫描
-->
<context:component-scan base-package="com.sb" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
<!-- 实例2
context:exclude-filter:设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.sb">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
5)——基于注解方式实现属性注入(可以使某个类无需创建set方法使用,
(1)Autowired:根据属性类型进行自动注入
// //定义Userdao类型属性,不需要添加set方法,因为Autowired已经封装了
// @Autowired //根据类型注入
// private Userdao userdao;
(2)Qualifier:根据属性名称进行注入,需要和Autowired一起使用
// //定义Userdao类型属性,不需要添加set方法,因为Autowired已经封装了
// @Autowired //根据类型注入
// @Qualifier(value = "userDaoImpl1")
// private Userdao userdao;
(3)Resource:可以根据类型注入,可以根据名称注入(由Javax拓展包中提供的,更建议使用1,2两种)
// @Resource //不加name,根据类型注入
@Resource(name = "userDaoImpl1") //加了name值之后则根据名称注入
private Userdao userdao;
(4)Value:注入普通类型属性
@Value(value = "abc") //value对属性值进行注入,注入之后name的值就为abc
private String name;
6)完全注解开发(纯注解,不使用xml配置文件)
(1)创建配置类,代替xml配置文件
(2)编写测试类
@Configuration //此注解说明这个类是配置类,用来代替xml配置文件
@ComponentScan(basePackages = {"com.完全注解开发","com.sb"})
public class SpringConfig {
}
浙公网安备 33010602011771号