本文转载自微信公众号《小明菜市场》,作者小明菜市场。转载本文请联系小明菜市场公众号。前言SpringBoot最大的特点是不需要XML配置文件,可以实现自动组装,全自动jar包配置。SpringBoot是微服务的核心,它的SpringCloud是基于SpringBoot的。它的框架用于简化Spring应用的初始构建和开发过程,即简化框架,方便开发。下面对SpringBoot的三个核心注解进行介绍。ConfigurationSpring4之后,官方推荐使用JavaConfig代替Application.xml声明,将Bean交给容器管理。在SpringBoot中,JavaConfig完全替代了application.xml,实现了xml的零配置。打开下面例子创建一个bean类publicclassSomeBean{publicvoiddoWork(){System.out.println("dowork...");其中dowork是创建Config类的逻辑方法@ConfigurationpublicclassConfig{@BeanpublicSomeBeansomeBean(){returnnewSomeBean();}}这里在Config类中添加@configuration注解,可以理解为配置类在春天。它的返回值是someBean,在someBean方法上加上@bean注解,返回的对象也会被Spring容器管理。简单测试publicclassTest{publicstaticvoidmain(String[]args){ApplicationContextcontext=newAnnotationConfigApplicationContext(Config.class);SomeBeansb=context.getBean(SomeBean.class);sb.doWork();}}这里创建并传入一个AnnotationConfigApplicationContext对象添加Config.class后,得到了someBean对象。dowork...Extended一般一个完整的bean需要包含,id,class,initMethod,destroyMethod,ref,scope。所以这里使用JavaConfig来配置这些属性。修改第一个示例代码.out.println("destroy...");}}添加、初始化、销毁方法@ConfigurationpublicclassConfig{@Bean(initMethod="init",destroyMethod="destroy")publicSomeBeansomeBean(){returnnewSomeBean();}}bean注解,属性指向对应的方法。publicclassTest{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(Config.class);SomeBeansb1=context.getBean(SomeBean.class);System.out.println(sb1);SomeBeansb2=context.getBean(SomeBean.class);System.out.println(sb2);context.close();}}输出结果为init...com.spring.SomeBean@16022d9dcom.spring.SomeBean@16022d9ddestroy...这样就完成了一个配置生命周期。@ComponentScan@ComponentScan注解主要用于类或接口上指定的扫描路径。Spring会自动将指定路径下带有指定注解的类组装到bean容器中。会自动组装的注解包括@Controller、@Service、@Component、@Repository等,其作用相当于
