Bean的配置
基于XML配置Bean
使用注解配置Bean
使用Java类提供Bean定义
!!常用:只需要在XML中开启context扫描即可实现Bean配置,省去了配置类
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 包扫描, 用注解的方式,配置bean
会扫描 指定包下,带@Component注解的类
并注入spring容器中,key是类名小写,value是类的对象
-->
<context:component-scan base-package="com.jt.springboot_demo_1.pojo" />
</beans>
使用注解定义Bean
使用 @Component 注解对类进行标注,使其可以被Spring容器识别,自动将 POJO 转换为容器可以管理的 Bean
另外 Spring 提供了三个和 @Component 等效的注解,分别用于DAO \ Service \ Controller
- @Repository 用于对 DAO 实现类进行标注
- @Service 用于对 Service 实现类进行标注
- @Controller 用于对 Controller 实现类进行标注
使用注解完成Bean注入
- @Autowired
使用该注解时,首先在容器中查询对应的Bean,如果查询不止一个,那么该注解会通过名称来查找
-
@Required
-
@Qualifer
@Autowired默认是单例的,可如果是接口就可能有多个实现类,为解决这一问题,引入该注解
- @Value
为属性设置默认值