2017-05-22 23 views
4

我使用@Configuration來配置cookies,而在我的項目中有2個包,我只想將配置應用到包中的一個。
有沒有什麼方法可以爲@Configuration設置目標包?春季啓動:只應用@Configuration到某個包只

封裝結構:
--app
----程序包A
------MyConfigClass.java
---- packageB

@EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 1800) 
@Configuration 
public class MyConfigClass extends WebMvcConfigurerAdapter { 
@Bean 
    public CookieSerializer cookieSerializer() { 
     // I want the follow cookie config only apply to packageA 
     DefaultCookieSerializer serializer = new DefaultCookieSerializer(); 
     serializer.setCookieName("myCookieName"); 
     serializer.setCookiePath("/somePath/"); 
     return serializer; 
    } 
} 

回答

0

其實,你可以使用@ComponentScan指定要掃描哪些程序包,並使用排除選項刪除要刪除的類的文件@EnableAutoConfiguration。你必須在你的主應用程序類中使用它。

@EnableAutoConfiguration(exclude = { Class1.class, 
     Class2.class, 
     Class3.class }, 
excludeName = {"mypackage.classname"})) 
@Configuration 
@ComponentScan(basePackages = { "mypackage" }) 
public class MyApplication { 

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

或者,您還可以提供要在配置文件中排除的類。

# AUTO-CONFIGURATION 
spring.autoconfigure.exclude= # Auto-configuration classes to exclude. 
+1

排除僅適用於記錄的自動配置。 –

1

在春天開機,你的主類用@SpringBootApplicatio註釋將包含@Configuration,@EnableAutoConfiguration@ComponentScan及其默認屬性,因此您的所有課程都將被自動掃描。在@SpringBootApplication中使用exclude只會排除類,但是如果包中包含很多類,代碼將顯得很糟糕。

在你的情況下,最簡單的方法是你的主要春季啓動應用程序入門級移動到要進行配置和自動掃描包:

----程序包A

---- --app

------MyConfigClass.java

---- packageB

0

如果你想像這樣細化,我根本不會使用組件掃描。 @SpringBootApplication是三樣東西的快捷方式:

  1. 啓用自動配置
  2. 在包凡春啓動的應用程序所在(包括子包)
  3. 確保春季啓動應用程序啓用組件掃描本身是一個配置(這樣就可以產生額外的豆,進口配置等

如果你想要一個春天啓動的應用程序,只在某些地方尋找配置,我會做這樣的事情:

@Configuration 
@EnableAutoConfiguration 
@Import(MyConfigClass.class) 
public class MySpringBootApp { ... } 

國際海事組織,它更清楚包括你想要在這種情況下,而不是使用排除掃描。也許你可能想重組你的應用程序,所以你不必首先這樣做?使用配置文件是一種選擇,以便這些不需要的配置僅適用於啓用配置文件時。