装配bean基于注解
一、用注解取代 xml 配置文件
- @Component
@Component(“id”)取代< bean id=" " class = " "> - web开发中,提供3个@Component注解衍生注解(功能一样)取代< bean class=" ">
- @Repository,dao层
- @Service,service层
- @Controller,web层
- 依赖注入,给私有字段设置,也可以给setter方法设置
- 方式一:按照【类型】注入;
@Autowired - 方式二:按照【名称】注入1
@Autowired
@Qualifier(“名称”) - 方式三:按照【名称】注入2
@Resource(“名称”)
- 生命周期
初始化:@PostConstruct
销毁:@PreDestroy - 作用域
@Scope(“prototype”) 多例
二、xml配置命名空间
注释使用前提,添加命名空间,让spring扫描含有注解类!!!
其中xmlns是XML namespace的缩写,命名空间详细内容可参考这里
schema命名空间分两部分
- 命名空间声明
默认:xmlns="" <标签名> --> < bean >
xmlns="http://www.springframework.org/schema/beans"
<xxx></xxx>
显示:xmlns:别名="" <别名:标签名> --> < context:…>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
<xsi:xxx id="">
<context:xxx id="">
- 确定schema xsd文件位置
xsi:schemaLocation=“名称 位置 名称2 位置2”
内容都是成对的【名称 位置】
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
配置好的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: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 id="userServiceId" class="com_itheima.c_ioc.UserSerivceImp" ></bean>
-->
<!-- 组件扫描 -->
<context:component-scan base-package="com_itheima.g_annotation_b_web"></context:component-scan>
</beans>