为什么要用到@Bean
当我们要使用第三方类实现组件注册到IOC容器时,例如第三方数据库连接池等,我们无法修改他们的代码,所以我们不能通过@Component及其衍生注解来进行组件定义。这是,可以通过@Bean注解把第三方组件注册到IOC容器中。
@Configuration
public class DaoConfig {
/**
* 使用bean注解生成 DruidDataSource实例并注册到IOC容器中。
* @return
* @throws IOException
*/
@Bean
public DruidDataSource dataSource() throws IOException {
DruidDataSource dataSource = new DruidDataSource();
//加载配置文件,作为数据源的初始化属性
Properties properties = PropertiesLoaderUtils.loadAllProperties("daoconfig/datasource-config.properties");
dataSource.setConnectProperties(properties);
//返回dataSource,spring会把他注册到IOC容器中。
return dataSource;
}
}
为什么要用到@Configuration
这里的@Configuration相当于xml注解中的<Beans>
上面的代码相当于
<?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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<!-- 相当于基于注解的启动类 AnnotationConfigApplicationContext-->
<context:annotation-config />
<bean class="com.xxx.DruidDataSource"/>
</beans>
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
当然,这里的@Configuration的作用也包含@Component,所以有时候我们配置MVC的拦截器时,就可以用到这个注解,表明这是个配置类
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginTicketInterceptor loginTicketInterceptor;
@Autowired
private LoginRequiredInterceptor loginRequiredInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginTicketInterceptor)
.excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");
registry.addInterceptor(loginRequiredInterceptor)
.excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");
}
}
但Spring检测到存在WebMvcConfigurer的实现类时,就不会自动注入配置了,而是使用我们的配置,所以这里的@Configuration的作用更多的是@Component,这里替换为@Component也是可以的