Bean定义
基于XML的配置
1 | <bean id="..." class="..."> |
基于注解的配置
@Component 在类上标注这个注解,且在XML上需要配置
1
2
3
4
5
6
7
8
9
10
11<context:component-scan/>
<!--类似这样-->
<!--负责包扫描配置组件-->
<context:component-scan base-package="com.lgq.cfw">
<!--exclude不扫描有Controller注解的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--只扫描控制器。 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>@Controller Web层
@Service Service层
@Repository DAO层
后面三个注解相当于@Component注解的分类,官方推荐使用后面三个,因为Spring会对这三个注解以后做扩展。
Bean名称
基于XML的配置
1 | <!--配置id或者name为...--> |
基于注解的配置
- @Component(“dataSource”)
配置一个id为dataSource的bean,这个类在IOC容器中的id就叫dataSource
Bean注入
基于XML的配置
通过配置property属性或者p命名空间,例如
1 | <!-- 将所有mapper接口的实现类自动加入到ioc容器中 --> |
基于注解的配置
@AutoWired 按类型注入
@Qualifier 按名称注入
@Value 普通属性
@Resource 对象属性
生命过程,Bean作用范围
基于XML的配置
- 生命周期 init-method, destory-method
- 范围 scope属性
基于注解的配置
@PostConstruct 初始化 相当于init-method
@PreDestory 销毁 相当于 destory-method
Scope 设置作用范围
适合场景
基于XML的配置
bean来自第三方
基于注解的配置
bean的实现类由用户自己开发