1. 程式人生 > 實用技巧 >多個@Configuration配置檔案,引用方式。多配置檔案引用時提示could not autowired時,沒有掃描到註解所在的包。

多個@Configuration配置檔案,引用方式。多配置檔案引用時提示could not autowired時,沒有掃描到註解所在的包。

當需要一個 Bean 初始化後,利用其例項方法或者其他巴拉巴拉,來初始化當前Bean ,引用方式。

引用方式

1、注入時新增 不必要 條件

2、新增 @DependsOn 或 @ConditionalOnBean註解,引數呼叫

3. 依賴不太複雜時,可使用 @Lazy 註解

配置類1

package cc.ash.config;

import cc.ash.bo.Course;
import cc.ash.bo.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*; @Slf4j @Configuration public class InitConfig { /** * 1、注入時新增 不必要 條件 * 2、新增 DependsOn 註解,引數呼叫其物件方法 * 3. 依賴不太複雜時,可使用 @Lazy 註解 */ @Autowired(required = false) Course course; /** * @Dependson註解是在另外一個例項建立之後才建立當前例項,也就是,最終兩個例項都會建立,只是順序不一樣 * * @ConditionalOnBean註解是隻有當另外一個例項存在時,才建立,否則不建立,也就是,最終有可能兩個例項都建立了,有可能只建立了一個例項,也有可能一個例項都沒建立
*/ @Bean @Scope("prototype") //singleton(預設)、prototype、request、session @DependsOn(value = {"course"}) public Student stu(Course course) { log.info(">>>>>>>>>>>>>>>>>>" + course.toString()); return new Student(); } }

配置類2

package cc.ash.config;

import cc.ash.bo.Course;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class InitialConfig {

    @Bean
    public Course course() {
        return new Course();
    }
}

啟動類

(不在基礎包下,新增基礎包掃描註解)

package cc.ash.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(value = "cc.ash")
@SpringBootApplication
public class PaymentMain8001 {

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

junit測試類

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PaymentMain8001.class)
public class Test {

}

.