GVKun编程网logo

Spring Boot在其他软件包上找到自动接线(spring boot自动装载)

24

如果您想了解SpringBoot在其他软件包上找到自动接线的相关知识,那么本文是一篇不可错过的文章,我们将对springboot自动装载进行全面详尽的解释,并且为您提供关于042springboot在

如果您想了解Spring Boot在其他软件包上找到自动接线的相关知识,那么本文是一篇不可错过的文章,我们将对spring boot自动装载进行全面详尽的解释,并且为您提供关于042 spring boot在启动之后,自动关闭、Spring Boot 2.0.0.M1:软件包org.springframework.boot.context.embed在哪里?、spring boot 怎么在其他类中使用 jparepository、spring boot 系列之六:深入理解spring boot的自动配置的有价值的信息。

本文目录一览:

Spring Boot在其他软件包上找到自动接线(spring boot自动装载)

Spring Boot在其他软件包上找到自动接线(spring boot自动装载)

我正在开发一个使用一些Spring Data Repository接口的Spring Boot应用程序:

package test;@SpringBootApplicationpublic class Application implements CommandLineRunner {    @Autowired    private  BookRepository repository;    . . .}

我可以看到BookRepository接口(在此后面)仅在与Application类位于同一包中时才能注入:

package test;public interface BookRepository extends MongoRepository<Book, String> {    public Book findByTitle(String title);    public List<Book> findByType(String type);    public List<Book> findByAuthor(String author);}

我可以在类上应用任何Spring Boot注释,以便能够在另一个包中找到BookRepository吗?

答案1

小编典典

在SpringBoot @SpringBootApplication旁边使用Spring
@ComponentScan批注并配置自定义基本包(您可以指定包名称列表或将使用其包的类列表),例如

@SpringBootApplication@ComponentScan(basePackages = {"otherpackage", "..."})public class Application

要么

@SpringBootApplication@ComponentScan(basePackageClasses = {otherpackage.MyClass.class, ...})public class Application

或从Spring 1.3.0(2016年12月)开始,您可以直接编写:

@SpringBootApplication(scanBasePackageClasses = {otherpackage.MyClass.class, ...})public class Application

请注意,组件扫描将在给定包的内部和下方找到类。

042 spring boot在启动之后,自动关闭

042 spring boot在启动之后,自动关闭

  在学校数据源的时候,还没有开始使用数据源,项目就关闭了。

  为了学习数据源,就只能使用测试类。

  但是,最近需要使用restful进行测试的时候,项目是关闭的,就很糟糕,不好进行测试。

1.日志如下:

 1 D:\jdk1.8.0_144\bin\java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:47661,suspend=y,server=n -Dfile.encoding=UTF-8 -classpath "D:\jdk1.8.0_144\jre\lib\charsets.jar;D:\jdk1.8.0_144\jre\lib\deploy.jar;D:\jdk1.8.0_144\jre\lib\ext\access-bridge-64.jar;D:\jdk1.8.0_144\jre\lib\ext\cldrdata.jar;D:\jdk1.8.0_144\jre\lib\ext\dnsns.jar;D:\jdk1.8.0_144\jre\lib\ext\jaccess.jar;D:\jdk1.8.0_144\jre\lib\ext\jfxrt.jar;D:\jdk1.8.0_144\jre\lib\ext\localedata.jar;D:\jdk1.8.0_144\jre\lib\ext\nashorn.jar;D:\jdk1.8.0_144\jre\lib\ext\sunec.jar;D:\jdk1.8.0_144\jre\lib\ext\sunjce_provider.jar;D:\jdk1.8.0_144\jre\lib\ext\sunmscapi.jar;D:\jdk1.8.0_144\jre\lib\ext\sunpkcs11.jar;D:\jdk1.8.0_144\jre\lib\ext\zipfs.jar;D:\jdk1.8.0_144\jre\lib\javaws.jar;D:\jdk1.8.0_144\jre\lib\jce.jar;D:\jdk1.8.0_144\jre\lib\jfr.jar;D:\jdk1.8.0_144\jre\lib\jfxswt.jar;D:\jdk1.8.0_144\jre\lib\jsse.jar;D:\jdk1.8.0_144\jre\lib\management-agent.jar;D:\jdk1.8.0_144\jre\lib\plugin.jar;D:\jdk1.8.0_144\jre\lib\resources.jar;D:\jdk1.8.0_144\jre\lib\rt.jar;E:\IDEA_Test\IDEA_springBoot\target\classes;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.0.6.RELEASE\spring-boot-starter-aop-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter\2.0.6.RELEASE\spring-boot-starter-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.0.6.RELEASE\spring-boot-autoconfigure-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.0.6.RELEASE\spring-boot-starter-logging-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\dell\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\dell\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;C:\Users\dell\.m2\repository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;C:\Users\dell\.m2\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;C:\Users\dell\.m2\repository\org\springframework\spring-aop\5.0.10.RELEASE\spring-aop-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-beans\5.0.10.RELEASE\spring-beans-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\aspectj\aspectjweaver\1.8.13\aspectjweaver-1.8.13.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.0.6.RELEASE\spring-boot-starter-web-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.0.6.RELEASE\spring-boot-starter-json-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.7\jackson-databind-2.9.7.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.7\jackson-core-2.9.7.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.7\jackson-datatype-jdk8-2.9.7.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.7\jackson-datatype-jsr310-2.9.7.jar;C:\Users\dell\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.7\jackson-module-parameter-names-2.9.7.jar;C:\Users\dell\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.13.Final\hibernate-validator-6.0.13.Final.jar;C:\Users\dell\.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\dell\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\dell\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\dell\.m2\repository\org\springframework\spring-web\5.0.10.RELEASE\spring-web-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-webmvc\5.0.10.RELEASE\spring-webmvc-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-context\5.0.10.RELEASE\spring-context-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-expression\5.0.10.RELEASE\spring-expression-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.0.6.RELEASE\spring-boot-starter-jdbc-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-jdbc\5.0.10.RELEASE\spring-jdbc-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-tx\5.0.10.RELEASE\spring-tx-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.0.6.RELEASE\spring-boot-starter-data-jpa-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\javax\transaction\javax.transaction-api\1.2\javax.transaction-api-1.2.jar;C:\Users\dell\.m2\repository\org\hibernate\hibernate-core\5.2.17.Final\hibernate-core-5.2.17.Final.jar;C:\Users\dell\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.2.Final\hibernate-jpa-2.1-api-1.0.2.Final.jar;C:\Users\dell\.m2\repository\org\javassist\javassist\3.22.0-GA\javassist-3.22.0-GA.jar;C:\Users\dell\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\dell\.m2\repository\org\jboss\jandex\2.0.3.Final\jandex-2.0.3.Final.jar;C:\Users\dell\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Users\dell\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.0.1.Final\hibernate-commons-annotations-5.0.1.Final.jar;C:\Users\dell\.m2\repository\org\springframework\data\spring-data-jpa\2.0.11.RELEASE\spring-data-jpa-2.0.11.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\data\spring-data-commons\2.0.11.RELEASE\spring-data-commons-2.0.11.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-orm\5.0.10.RELEASE\spring-orm-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-aspects\5.0.10.RELEASE\spring-aspects-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\apache\tomcat\tomcat-jdbc\8.5.34\tomcat-jdbc-8.5.34.jar;C:\Users\dell\.m2\repository\org\apache\tomcat\tomcat-juli\8.5.34\tomcat-juli-8.5.34.jar;C:\Users\dell\.m2\repository\com\zaxxer\HikariCP\2.7.9\HikariCP-2.7.9.jar;C:\Users\dell\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\dell\.m2\repository\org\apache\commons\commons-dbcp2\2.2.0\commons-dbcp2-2.2.0.jar;C:\Users\dell\.m2\repository\org\apache\commons\commons-pool2\2.5.0\commons-pool2-2.5.0.jar;C:\Users\dell\.m2\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-starter-test\2.0.6.RELEASE\spring-boot-starter-test-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-test-autoconfigure\2.0.6.RELEASE\spring-boot-test-autoconfigure-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\com\jayway\jsonpath\json-path\2.4.0\json-path-2.4.0.jar;C:\Users\dell\.m2\repository\net\minidev\json-smart\2.3\json-smart-2.3.jar;C:\Users\dell\.m2\repository\net\minidev\accessors-smart\1.2\accessors-smart-1.2.jar;C:\Users\dell\.m2\repository\org\ow2\asm\asm\5.0.4\asm-5.0.4.jar;C:\Users\dell\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\dell\.m2\repository\org\assertj\assertj-core\3.9.1\assertj-core-3.9.1.jar;C:\Users\dell\.m2\repository\org\mockito\mockito-core\2.15.0\mockito-core-2.15.0.jar;C:\Users\dell\.m2\repository\net\bytebuddy\byte-buddy\1.7.11\byte-buddy-1.7.11.jar;C:\Users\dell\.m2\repository\net\bytebuddy\byte-buddy-agent\1.7.11\byte-buddy-agent-1.7.11.jar;C:\Users\dell\.m2\repository\org\objenesis\objenesis\2.6\objenesis-2.6.jar;C:\Users\dell\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\dell\.m2\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;C:\Users\dell\.m2\repository\org\skyscreamer\jsonassert\1.5.0\jsonassert-1.5.0.jar;C:\Users\dell\.m2\repository\com\vaadin\external\google\android-json\0.0.20131108.vaadin1\android-json-0.0.20131108.vaadin1.jar;C:\Users\dell\.m2\repository\org\springframework\spring-core\5.0.10.RELEASE\spring-core-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-jcl\5.0.10.RELEASE\spring-jcl-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\spring-test\5.0.10.RELEASE\spring-test-5.0.10.RELEASE.jar;C:\Users\dell\.m2\repository\org\xmlunit\xmlunit-core\2.5.1\xmlunit-core-2.5.1.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-configuration-processor\2.0.6.RELEASE\spring-boot-configuration-processor-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot-test\2.0.6.RELEASE\spring-boot-test-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\springframework\boot\spring-boot\2.0.6.RELEASE\spring-boot-2.0.6.RELEASE.jar;C:\Users\dell\.m2\repository\org\mybatis\spring\boot\mybatis-spring-boot-starter\1.3.1\mybatis-spring-boot-starter-1.3.1.jar;C:\Users\dell\.m2\repository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\1.3.1\mybatis-spring-boot-autoconfigure-1.3.1.jar;C:\Users\dell\.m2\repository\org\mybatis\mybatis\3.4.5\mybatis-3.4.5.jar;C:\Users\dell\.m2\repository\org\mybatis\mybatis-spring\1.3.1\mybatis-spring-1.3.1.jar;D:\IntelliJ IDEA 2017.2\lib\idea_rt.jar" com.springBoot.springbootAndMybatis.ApplicationTest.Application
 2 Connected to the target VM, address: ''127.0.0.1:47661'', transport: ''socket''
 3 
 4   .   ____          _            __ _ _
 5  /\\ / ___''_ __ _ _(_)_ __  __ _ \ \ \ \
 6 ( ( )\___ | ''_ | ''_| | ''_ \/ _` | \ \ \ \
 7  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 8   ''  |____| .__|_| |_|_| |_\__, | / / / /
 9  =========|_|==============|___/=/_/_/_/
10  :: Spring Boot ::        (v2.0.6.RELEASE)
11 
12 2018-12-05 22:04:03.377  INFO 2360 --- [           main] c.s.s.ApplicationTest.Application        : Starting Application on DESKTOP-TQ4OD79 with PID 2360 (E:\IDEA_Test\IDEA_springBoot\target\classes started by dell in E:\IDEA_Test\IDEA_springBoot)
13 2018-12-05 22:04:03.383  INFO 2360 --- [           main] c.s.s.ApplicationTest.Application        : The following profiles are active: dev
14 2018-12-05 22:04:03.452  INFO 2360 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@353352b6: startup date [Wed Dec 05 22:04:03 CST 2018]; root of context hierarchy
15 2018-12-05 22:04:04.170  WARN 2360 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in ''[com.springBoot.springbootAndMybatis.ApplicationTest]'' package. Please check your configuration.
16 2018-12-05 22:04:04.930  INFO 2360 --- [           main] com.zaxxer.hikari.HikariDataSource       : DatebookHikariCP - Starting...
17 2018-12-05 22:04:05.186  INFO 2360 --- [           main] com.zaxxer.hikari.HikariDataSource       : DatebookHikariCP - Start completed.
18 2018-12-05 22:04:05.244  INFO 2360 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit ''default''
19 2018-12-05 22:04:05.271  INFO 2360 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
20     name: default
21     ...]
22 2018-12-05 22:04:05.373  INFO 2360 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.2.17.Final}
23 2018-12-05 22:04:05.375  INFO 2360 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
24 2018-12-05 22:04:05.431  INFO 2360 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
25 2018-12-05 22:04:05.606  INFO 2360 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
26 2018-12-05 22:04:06.285  INFO 2360 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit ''default''
27 2018-12-05 22:04:06.971  INFO 2360 --- [           main] c.s.s.ApplicationTest.Application        : Started Application in 4.077 seconds (JVM running for 4.994)
28 2018-12-05 22:04:06.974  INFO 2360 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@353352b6: startup date [Wed Dec 05 22:04:03 CST 2018]; root of context hierarchy
29 2018-12-05 22:04:06.976  INFO 2360 --- [       Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit ''default''
30 2018-12-05 22:04:06.977  INFO 2360 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : DatebookHikariCP - Shutdown initiated...
31 Disconnected from the target VM, address: ''127.0.0.1:47661'', transport: ''socket''
32 2018-12-05 22:04:06.995  INFO 2360 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : DatebookHikariCP - Shutdown completed.
33 
34 Process finished with exit code 0

 

2.解决 方式

  后来百度了,不外乎是两种方式。

  一种加入spring-boot-starter-web依赖,但是这个我在创建springboot项目的时候就存在了。

  然后,还有一种说法,我实验了一下是可以的。

  将provided去掉:

   

 

Spring Boot 2.0.0.M1:软件包org.springframework.boot.context.embed在哪里?

Spring Boot 2.0.0.M1:软件包org.springframework.boot.context.embed在哪里?

Spring Boot1.5.3.RELEASE有几类org.springframework.boot.context.embed,并在子包jettytomcatundertow。但是,https://github.com/spring-projects/spring-boot/tree/v2.0.0.M1/spring-boot/src/main/java/org/springframework/boot/context不再包含子目录embed

哪里上课TomcatEmbeddedServletContainerFactory了?

spring boot 怎么在其他类中使用 jparepository

spring boot 怎么在其他类中使用 jparepository

目前我只会通过在 

@RestController

中注释

@Autowired

使用 jparepository

请问有其他方法 new 一个 jparepository 吗?或者在非 Controller 下使用 jparepository

spring boot 系列之六:深入理解spring boot的自动配置

spring boot 系列之六:深入理解spring boot的自动配置

我们知道,spring boot自动配置功能可以根据不同情况来决定spring配置应该用哪个,不应该用哪个,举个例子:

  • Spring的JdbcTemplate是不是在Classpath里面?如果是,并且DataSource也存在,就自动配置一个JdbcTemplate的Bean
  • Thymeleaf是不是在Classpath里面?如果是,则自动配置Thymeleaf的模板解析器、视图解析器、模板引擎

那个这个是怎么实现的呢?原因就在于它利用了Spring的条件化配置,条件化配置允许配置存在于应用中,但是在满足某些特定条件前会忽略这些配置。

要实现条件化配置我们要用到@Conditional条件化注解。

本篇随便讲从如下三个方面进行展开:

  1. @Conditional小例子,来说明条件化配置的实现方式
  2. spring boot 的条件化配置详解
  3. spring boot 自动配置源码分析
  4. 自己动手实现spring boot starter pom

一、@Conditional小例子

我们知道在windows下显示列表的命令是dir,而在linux系统下显示列表的命令是ls,基于条件配置,我们可以实现在不同的操作系统下返回不同的值。

  1. 判断条件定义
    1. )windows下的判定条件
      复制代码
      /**
       * 实现spring 的Condition接口,并且重写matches()方法,如果操作系统是windows就返回true
       *
       */
      public class WindowsCondition implements Condition{
      
          @Override
          public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              
              return context.getEnvironment().getProperty("os.name").contains("Windows");
          }
      
          
      }
      复制代码
    2. )linux下的判定条件
      复制代码
      /**
       * 实现spring 的Condition接口,并且重写matches()方法,如果操作系统是linux就返回true
       *
       */
      public class LinuxCondition implements Condition{
      
          @Override
          public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              
              return context.getEnvironment().getProperty("os.name").contains("Linux");
          }
      
          
      }
      复制代码
  2. 不同系统下的Bean的类
    1. )接口
      public interface ListService {
      
          public String showListLine();
      }
    2. )windows下的Bean类
      复制代码
      public class WindowsListService implements ListService{
      
          @Override
          public String showListLine() {
              return "dir";
          }
      
      }
      复制代码
    3. )linux下的Bean的类
      复制代码
      public class LinuxListService implements ListService{
      
          @Override
          public String showListLine() {
              return "ls";
          }
      
      }
      复制代码
  3. 配置类
    复制代码
    @Configuration
    public class ConditionConfig {
    
        /**
         * 通过@Conditional 注解,符合windows条件就返回WindowsListService实例
         * 
         */
        @Bean
        @Conditional(WindowsCondition.class)
        public ListService windonwsListService() {
            return new WindowsListService();
        }
    
        /**
         * 通过@Conditional 注解,符合linux条件就返回LinuxListService实例
         * 
         */
        @Bean
        @Conditional(LinuxCondition.class)
        public ListService linuxListService() {
            return new LinuxListService();
        }
    }
    复制代码
  4. 测试类
    复制代码
    public class ConditionTest {
    
        public static void main(String[] args) {
    
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
            ListService listService = context.getBean(ListService.class);
            System.out
                    .println(context.getEnvironment().getProperty("os.name") + " 系统下的列表命令为: " + listService.showListLine());
        }
    }
    复制代码
  5. 运行测试类,由于我的是windows7 系统,因此结果是
    Windows 7 系统下的列表命令为: dir

    如果你的是linux系统,则结果就会是

    Linux 系统下的列表命令为: ls

二、spring boot 的条件化配置

在spring boot项目中会存在一个名为spring-boot-autoconfigure的jar包

条件化配置就是在这个jar里面实现的,它用到了如下的条件化注解,这些注解都是以@ConditionalOn开头的,他们都是应用了@Conditional的组合注解:

接下来我们看个源码的列子:

以JdbcTemplateAutoConfiguration为例,它里面有这段代码:

@Bean
    @Primary
    @ConditionalOnMissingBean(JdbcOperations.class)
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(this.dataSource);
    }

只有在不存在JdbcOperations(如果查看JdbcTemplate的源码,你会发现JdbcTemplate类实现了JdbcOperations接口)实例的时候,才会初始化一个JdbcTemplate 的Bean。

基于以上内容,我们就可以阅读自动配置相关的源码了。

 

三、spring boot 自动配置源码分析

spring boot项目的启动类用的注解--@SpringBootApplication是一个组合注解,其中@EnableAutoConfiguration是自动配置相关的。

而这个@EnableAutoConfiguration注解里面有个@Import注解导入了EnableAutoConfigurationImportSelector用来实现具体的功能

(注:由于我本地的spring boot版本不是最新的,这里的EnableAutoConfigurationImportSelector已经不建议使用了,新版本可能已经换成了其他类,但是不影响我们看代码)

 这个类继承了AutoConfigurationImportSelector

进入父类,里面有个方法selectImports()调用了方法getCandidateConfigurations(),进而调用了SpringFactoriesLoader.loadFactoryNames()方法

在SpringFactoriesLoader.loadFactoryNames()方法里面,我们看到会查询META-INF/spring.factories这个配置文件

SpringFactoriesLoader.loadFactoryNames方法会扫描具有META-INF/spring.factories文件的jar包,而我们的spring-boot-autoconfigure.jar里面就有一个这样的文件,此文件中声明了具体有哪些自动配置:

我们上面提到的JdbcTemplateAutoConfiguration自动配置类就在里面。

 四、编写自己的spring boot starter pom

接下来,我们就来写一个简单的spring boot starter pom。

步骤如下:

  1. 新建starter maven项目spring-boot-starter-hello
  2. 修改pom文件
    复制代码
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.sam</groupId>
        <artifactId>spring-boot-starter-hello</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <dependencies>
            <!-- 这里需要引入spring boot的自动配置作为依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-autoconfigure</artifactId>
                <version>1.5.1.RELEASE</version>
            </dependency>
    
    
        </dependencies>
    </project>
    复制代码
  3. 属性配置
    复制代码
    /**
     * @ConfigurationProperties
     * 自动匹配application.properties文件中hello.msg的值,然后赋值给类属性msg,这里的msg默认值为“spring boot”
     *
     */
    @ConfigurationProperties(prefix="hello")
    public class HelloServiceProperties {
    
        private static final String MSG = "spring boot";
        
        private String msg = MSG;
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
        
        
    }
    复制代码
  4. 判定依据类
    复制代码
    /**
     * 后面的代码会依据此类是否存在,来决定是否生产对应的Bean
     *
     */
    public class HelloService {
    
        private String msg;
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public String sayHello() {
            return "hello " + msg;
        }
    }
    复制代码
  5. 自动配置类
    复制代码
    @Configuration
    @EnableConfigurationProperties(HelloServiceProperties.class)
    @ConditionalOnClass(HelloService.class)
    @ConditionalOnProperty(prefix = "hello", matchIfMissing = true, value = "enabled")
    public class HelloServiceAutoConfiguration {
    
        @Autowired
        HelloServiceProperties helloServiceProperties;
    
        @Bean
        @ConditionalOnMissingBean(HelloService.class)
        public HelloService helloService() {
            HelloService service = new HelloService();
            service.setMsg(helloServiceProperties.getMsg());
            return service;
        }
    }
    复制代码

    根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass(HelloService.class)判定HelloService这个类在Classpath中是否存在,存在并且还没有对应的Bean,就生成对应的helloService Bean

  6. 注册配置,需要到META-INF/spring.factories文件中注册改自动配置类:在src/main/source目录下新建改文件,然后进行配置。
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.sam.spring_boot_starter_hello.HelloServiceAutoConfiguration
  7. 对该工程进行mvn clean install,将jar推送到本地maven仓库,供后续使用。
  8. 使用starter ,使用我们这个starter 需要新建一个或使用既存的一个spring boot工程(这里我用的是既存的),然后
    1. )修改pom,引入上述的依赖
      <dependency>
                  <groupId>com.sam</groupId>
                  <artifactId>spring-boot-starter-hello</artifactId>
                  <version>0.0.1-SNAPSHOT</version>
              </dependency>
    2. )实现controller
      复制代码
      @RestController
      public class HelloController {
        //代码中没有配置这个helloService Bean,但是自动配置能够帮忙实例化,因此可以直接注入
          @Autowired
          HelloService helloService;
          
          @RequestMapping(value="/helloService")
          public String sayHello() {
              return helloService.sayHello();
          }
      }
      复制代码
    3. )页面访问/helloService接口

       

    4. )在application.properties里面配置hello.msg=sam,然后再次访问/helloService接口

       

关于Spring Boot在其他软件包上找到自动接线spring boot自动装载的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于042 spring boot在启动之后,自动关闭、Spring Boot 2.0.0.M1:软件包org.springframework.boot.context.embed在哪里?、spring boot 怎么在其他类中使用 jparepository、spring boot 系列之六:深入理解spring boot的自动配置等相关知识的信息别忘了在本站进行查找喔。

本文标签: