SpringBoot中@Configuration注解

一、背景

在spring框架中,会有大量 的xml配置文件,或者需要做很多繁琐的配置。

从spring3开始,spring就支持了两种bean的配置方式, 一种是基于xml文件方式、另一种就是JavaConfig 。

springboot 框架是为了能够帮助使用 spring 框架的开发者快速高效的构建一个基于 spirng 框架以及 spring 生态 体系的应用解决方案。它是对约定优于配置这个理念下 的一个最佳实践。因此它是一个服务于框架的框架,服务的范围是简化配置文件

约定优于配置的体现

  • maven的目录结构

    • 默认有resources文件夹存放配置文件
    • 默认打包方式为jar
  • spring-boot-starter-web 中默认包含 spring mvc 相关依赖以及内置的tomcat容器,使得构建一个web应用 更加简单

  • 默认提供application.properties/yml文件

  • 默认通过 spring.profiles.active 属性来决定运行环境时读取的配置文件

  • EnableAutoConfiguration 默认对于依赖的starter进行自动装载

Spring4 以后,官方推荐我们使用Java Config来代替applicationContext.xml,声明将Bean交给容器管理。

在Spring Boot中,Java Config的使用也已完全替代了applicationContext.xml。实现了xml的零配置。在实现JavaConfig配置的时候就需要使用@Configuration和@Bean注解。

二、注解@Configure的作用

@Configuration的作用:标注在类上,配置spring容器(应用上下文)。相当于把该类作为spring的xml配置文件中的<beans>。@Configuration注解的类中,使用@Bean注解标注的方法,返回的类型都会直接注册为bean。

@Configure注解的定义如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    
    
    String value() default "";
}

从定义来看,底层是含有@Component ,所以@Configuration 具有和 @Component 的作用。因此context:component-scan/或者@ComponentScan都能处理@Configuration注解的类。

三、JavaConfig和xml的异同

传统意义上的 spring 应用都是基于 xml 形式来配置 bean 的依赖关系。然后通过spring容器在启动的时候,把bean进行初始化并且,如果bean之间存在依赖关系,则分析这些已经在IoC容器中的bean根据依赖关系进行组装。 Java5 引入了 Annotations 这个特性,Spring 框架也紧随大流并且推出了基于 Java 代码和Annotation元信息的依赖关系绑定描述的方式,也就是JavaConfig。

任何一个标注了@Configuration 的 Java 类定义都是一个 JavaConfig 配置类。而在这个配置类中,任何标注了 @Bean 的方法,它的返回值都会作为 Bean 定义注册到 Spring的IOC容器,方法名默认成为这个bean的id。和之前XML配置的作用是一样的。

具体的相同之处:
1、@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)
2、@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,作用为:注册bean对象

1、表达形式层面

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)

基于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"        
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"        
        default-lazy-init="true">
     
	<!--bean定义-->
 </beans>

而基于JavaConfig的配置方式是这样,任何一个标注了@Configuration的Java类定义都是一个JavaConfig配置类:

@Configuration 
public class MockConfiguration
{
    
    
     //bean定义
 }

2、注册bean定义层面

基于XML的配置形式是这样,其中id是bean的唯一标识符,class是指定bean的Java类名称。

<bean id="mockService" class="..MockServiceImpl"> 
     ...
</bean>

而基于JavaConfig的配置形式是这样的:

@Configuration
public class MockConfiguration
{
    
    
     
	@Bean
	public MockService mockService(){
    
    
         return new MockServiceImpl(); //相当于实例化MockServiceImpl,并交给容器管理
     }
}

任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,如果不定义名字,方法名将默认成该bean定义的id。返回的类型即为注册bean的类型。

3、表达依赖注入关系层面

为了表达bean与bean之间的依赖关系,在XML形式中一般是这样:

 <bean id="mockService" class="..MockServiceImpl">
     <!--此处的ref是指bean配置文件中的bean名称-->
     <property name="dependencyService" ref="dependencyService" />
 </bean>

 <bean id="dependencuService" class="DependencyServiceImpl"> </bean>

而基于JavaConfig的配置形式是这样的:

@Configuration
public class MockConfiguration
{
    
         
	@Bean
	public MockService mockService(){
    
      
			return new MockServiceImpl(dependencyService());
 	}

     
	@Bean     
	public DependencyService dependencyService(){
    
    
		return new DependencyServiceImpl();
	 }
 }

如果一个bean的定义依赖其他bean,则直接调用对应的JavaConfig类中依赖bean的创建方法就可以了。

四、两种方法配置Mybatis

祈雨的博文中,展示了分别用JavaConfig和xml配置mybatis的代码。可以很容易看出JavaConfig和xml的区别。

1、通过JavaConfig进行配置

@Configuration
public class TestMybaitsConf {
    
    

    @Bean
    public DataSource dataSource() {
    
    
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
    
    
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://192.168.100.25:6660/TXSMS?useUnicode=true&amp;characterEncoding=utf-8");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
    
    
        SqlSessionFactory factory = null;
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setConfigLocation(resolver.getResource("classpath:mybatis.xml"));
        try {
    
    
            factory = bean.getObject();
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
        return factory;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    
    
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
    
    
        return new DataSourceTransactionManager(dataSource);
    }
}

2、使用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"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/jee  http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        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/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://192.168.100.25:6660/TXSMS?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

参考文章:
[1]:https://mp.weixin.qq.com/s/y6YgXVnXGX8f7OGuGVyRIw
[2]:https://www.cnblogs.com/wenq001/p/9261496.html
[3]:https://blog.csdn.net/sz85850597/article/details/79133242

猜你喜欢

转载自blog.csdn.net/loongkingwhat/article/details/105752446