引言

最近在看spring cloud的项目,作为微服务,常常会把一些公共的类库(比如工具类等)抽离出作为公共模块。spring boot项目在启动时,会扫描自己包下面的类到spring容器。如果不在包下面就不会被spring管理。

比如写的公共redis操作模块,在启动的时候报错如下。

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in cn.yiidii.security.TestController required a bean of type 'cn.yiidii.cache.RedisOps' that could not be found.


Action:

Consider defining a bean of type 'cn.yiidii.cache.RedisOps' in your configuration.

Disconnected from the target VM, address: '127.0.0.1:51724', transport: 'socket'

Process finished with exit code 0

cache包结构如下

├───copter-cache
│   │   copter-cache.iml
│   │   pom.xml
│   │
│   ├───src
│   │   └───main
│   │       ├───java
│   │       │   └───cn
│   │       │       └───yiidii
│   │       │           └───cache
│   │       │               │   NullVal.java
│   │       │               │   RedisConfig.java
│   │       │               │   RedisOps.java
│   │       │               │
│   │       │               ├───config
│   │       │               │       RedisObjectSerializer.java
│   │       │               │
│   │       │               └───lock
│   │       │                       RedisDistributedLock.java

spring boot项目包如下

├───src
│   ├───main
│   │   ├───java
│   │   │   └───cn
│   │   │       └───yiidii
│   │   │           └───security
│   │   │                   SecurityDemoApplication.java
│   │   │                   TestController.java
│   │   │
│   │   └───resources
│   │           application.yml

SecurityDemoApplication不能加载cn.yiidii.cache包下的Bean

@Import

一种做法是在启动类上增加需要被管理的这些类的class

@SpringBootApplication
@Import({RedisConfig.class})
public class SecurityDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityDemoApplication.class, args);
    }

}

启动成功

spring.factories

resources目录下新建一个META-INF 的目录,然后在META-INF下新建一个spring.factories 的文件,里面的内容为:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.yiidii.cache.RedisConfig

这样spring就能加载cn.yiidii.cache.RedisConfig并管理RedisConfig

这样就能实现加载一个Spring 不能扫描到的一个类,只要是Spring Boot 默认扫描路径不能够扫描到,都可以使用这种方式去加载!!!

  • 分类: JAVA
  • 标签: 无