1、配置bean的注解
1.1、扫描注解
想要使用注解配置bean,必须在spring配置文件添加包扫描:
<?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">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="service"></context:component-scan>
<context:component-scan base-package="dao"></context:component-scan>
</beans>
1.2、@Component及其衍生注解
@Component是用于配置bean的,添加该注解的类实际上相当于在Spring配置文件中使用bean标签。
- 作用:把当前类对象存入spring容器中
- 属性:
- value:用于指定bean的id。当我们不写时,它的默认值是当前类名首字母改小写
@Controller:一般用在表现层
@Service:一般用在业务层
@Repository:一般用在持久层
以上三个注解和@Component的作用是一致的,只是语义更加清晰。
2、依赖注入的注解
依赖注入的常用注解有四个:
@Autowired:
- 作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功;
- 位置:变量上,或者方法上
- 注意:
- 如果容器中没有任何bean的类型和与之匹配,则报错;
- 当容器中有多个类型匹配时,如果变量名与bean的id相同时,便会使用该bean;如果没有,就会报错。
@Qualifier:
- 作用:在按照类中注入的基础之上再按照名称注入,与@Autowired共同使用
- 属性:
- value:用于指定注入bean的id。
@Resource
- 作用:直接按照bean的id注入。它可以独立使用
- 属性:
- name:用于指定bean的id。
@Value
- 作用:用于注入基本类型和String类型的数据
- 属性:
- value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
- SpEL的写法:${表达式}
3、作用范围
设置bean的作用范围的注解是@Scope
@Scope
- 作用:用于指定bean的作用范围
- 属性:
- value:指定范围的取值。常用取值:singleton、prototype
- 位置:作用在类或方法上,指定bean的作用范围
4、生命周期
指定生命周期的注解有两个@PostConstruct、@PreDestroy,两个注解均是写在方法上
-
@PostConstruct
- 作用:用于指定初始化方法
-
@PreDestroy
- 作用:用于指定销毁方法
5、配置文件的注解
5.1、注解详解
使用下面一些注解,便可以做到真正的”零配置“:包括@Configuration、@ComponentScan、@Bean、@Import、@PropertySource
@Configuration
- 作用:指定当前类是一个配置类,相当于Spring的配置xml文件
@ComponentScan
- 作用:指定spring在创建容器时要扫描的包,相当于标签<context:component-scan base-package="">
- 属性:
- value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
@Bean
- 作用:用于把当前方法的返回值作为bean对象,并存入spring的容器中
- 属性:
- name:用于指定bean的id,当不写时,默认值是当前方法的名称
- 注意:如果方法有参数,则会去容器中查找有没有可用的bean对象。查找的方式和Autowired注解的作用是一样的。
@Import
- 作用:用于导入其他的配置类
- 属性:
- value:用于指定其他配置类的字节码。
- 注意:当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
@PropertySource
- 作用:用于指定properties文件的位置
- 属性:
- value:指定文件的名称和路径。
关键字:classpath,表示类路径下
- value:指定文件的名称和路径。
5.2、案例
package config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@ComponentScan(basePackages = {"dao","service"})
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@Bean(name="runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("dataSource1") DataSource dataSource){
return new QueryRunner(dataSource);
}
}
有错误的地方敬请指出,欢迎大家评论区或者私信交流!每日持续更新Java、Python、大数据技术,请大家多多关注!