本文共 2437 字,大约阅读时间需要 8 分钟。
【重要区别】
@Component:会当做配置类,但不会为其生成CGLIB代理class,多例。例如@Controller、@Service等底层还是@Component注解。@Configuration:会当做配置类,但会为其生成CGLIB代理class,走代理的会是单例。
在获取当前类名时,使用@Component获取的是当前类名;而@Configuration获取的是当前类名+唯一标识(CGLIB代理)
关于代理,另一篇博文做了详细的示例,参见
【一般区别】
@Configuration本质上还是@Component。@Configuration标记的类必须符合下面的要求:
Spring 容器在启动时,会加载默认的一些PostPRocessor,其中就有ConfigurationClassPostProcessor,
这个后置处理程序专门处理带有@Configuration注解的类,这个程序会在bean 定义加载完成后,在bean初始化前进行处理。@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。
Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
bean创建完成空对象,就开始进行@Autowire、@PostConstruct赋值
其作用顾名思义,就是将一个配置类在另一个配置类之后加载。
研究初衷:
本人公司使用了Pagehelper,它的实现原理是Mybatis Plugin,也就是拦截器。根据拦截器的加载机制,后加载的先执行,由于某种原因(例如要兼容其他国产数据库),我需要在他之前拦截到SQL语句,这就要求拦截器要加载在MybatisAutoConfiguration之后。package cn.com.infosec.netseal.webserver.config.datasource;import cn.com.infosec.netseal.common.config.ConfigUtil;import cn.com.infosec.netseal.common.exceptions.ToLogException;import com.github.pagehelper.PageInterceptor;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;import java.util.List;import java.util.Properties;/** * @Description 自定义分页插件自动装配策略,使用自定义配置文件 * @Author lhx */@Configuration@AutoConfigureAfter(MybatisAutoConfiguration.class)public class PageHelperAutoConfiguration { @Autowired private ListsqlSessionFactoryList; @PostConstruct public void addPageInterceptor() { //pageHelper的sql分页拦截器 PageInterceptor interceptor = new PageInterceptor(); //读取自定义的配置文件 try { Properties sqlDialect = ConfigUtil.getInstance().getSqlDialect(); // System.out.println(sqlDialect); interceptor.setProperties(sqlDialect); } catch (Exception e) { throw new ToLogException("读取配置发生错误", e); } //将分页拦截器添加到mybatis的sqlsession for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) { sqlSessionFactory.getConfiguration().addInterceptor(interceptor); } }}
转载地址:http://qzqgn.baihongyu.com/