簡體   English   中英

Spring Boot從另一個模塊加載bean之前

[英]Spring Boot load beans from a different module before

我有兩個Maven模塊:

api-module
commons-module

api模塊包含軟件包com.example.api ,commons模塊包含軟件包com.example.commons

當我運行主應用程序com.example.api.ApiMain時 ,執行失敗。 這是因為我在commons包中定義了Mongo Repository類。 API控制器依賴於它們,並且由於它們沒有在api bean之前實例化,因此執行失敗。

這是主要的API應用程序:

package com.example.api;

@SpringBootApplication
@ComponentScan({"com.example.commons", "com.example.api"})
public class ApiMain {
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

如何確保在加載com.example.api中的bean之前已掃描com.example.commons組件?

我可以在com.example.api中的每個bean上使用@DependsOn注釋,但是有幾個類,將來還會添加更多的類,這會使代碼變得丑陋。

如果有一種方法可以指示彈簧首先從公共模塊加載組件,則可以解決此問題。

您可以指導我如何執行此操作。

不管首先掃描哪個包都沒有關系,因為Spring會構建一個依賴圖並找出實例化bean的順序。 如果您希望某些bean在其他bean之前被實例化,比如說BeanA依賴於BeanB ,那么BeanA將具有一個構造函數@Autowired BeanA(BeanB b)

弄清楚實例化的順序是Spring Dependency Injection的基本方面,我建議您進一步閱讀Spring DI,因為我不認為您掌握了控制反轉的概念以及Spring DI的作用。

但是對我來說聽起來像是您有以下內容:

public class BeanA {
    @Autowired
    BeanB b;
    public BeanA() {
        b.doSomething();
    }
}

但是當BeanA的構造函數時b仍然為null。 因為您正在使用BeanBBeanA中執行某種實例化, BeanB您將獲得NullPointerException ,而必須具有: BeanA(BeanB b)

我面臨着同樣的問題。 我將以下代碼用於Rest API控制器

@RestController
@EnableOAuth2Sso
@EnableResourceServer
@SpringBootApplication
public class SpringBootWebApplication extends WebSecurityConfigurerAdapter {

    //Dependancy injection using autowire
    @Autowired
    OAuth2ClientContext oauth2ClientContext;
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

將此代碼用於呈現我的HTML頁面的普通控制器

@Configuration
@EnableAutoConfiguration
@Controller
public class WelcomeController {

試試這個,讓我知道這是否可行,或者您仍有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM