Spring boot Spring boot:仅将@Configuration应用于某些包

Spring boot Spring boot:仅将@Configuration应用于某些包,spring-boot,configuration,setcookie,Spring Boot,Configuration,Setcookie,我正在使用@Configuration配置cookies,而在我的项目中有两个包,我只想将配置应用于其中一个包。 有没有办法为@Configuration设置目标包 包结构: --应用程序 ----包装a ------MyConfigClass.java ----包装B @EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 1800) @Configuration public class MyConfigClass extends WebM

我正在使用
@Configuration
配置cookies,而在我的项目中有两个包,我只想将配置应用于其中一个包。
有没有办法为
@Configuration
设置目标包

包结构:
--应用程序
----包装a
------MyConfigClass.java
----包装B

@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;
    }
}

您可以尝试使用@ComponentScan(“packageA”)


选中Spring Boot中的

,用
@springbootapplication
注释的主类将已经包括
@Configuration
@EnableAutoConfiguration
@ComponentScan
及其默认属性,因此所有类都将被自动扫描。在
@SpringBootApplication
中使用
exclude
只会排除类,但是如果包中有很多类,代码看起来会很糟糕

在您的情况下,最简单的方法是将主Spring Boot应用程序条目类移动到要配置和自动扫描的包中:

----包装

------应用程序

------MyConfigClass.java


----packageB

实际上,您可以使用
@ComponentScan
指定要扫描的包,并使用
@EnableAutoConfiguration
和exclude选项忽略要忽略的类。您必须在主应用程序类中使用它

@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.

如果您想像这样进行细粒度处理,我根本不会使用组件扫描
@SpringBootApplication
是三件事的快捷方式:

  • 启用自动配置
  • 在spring boot应用程序所在的包(包括子包)中启用组件扫描
  • 确保spring引导应用程序本身是一个配置(这样您就可以贡献额外的bean、导入配置等)
  • 如果您想要一个只在特定位置查找配置的Spring引导应用程序,我会这样做:

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

    在我看来,在这样的场景中包含您想要的内容比使用排除扫描要清楚得多。也许您可能想重新构造应用程序,这样您就不必一开始就这样做了?使用配置文件是一个选项,这样这些不需要的配置只会在启用配置文件时适用。

    我已经添加了,但cookie是无效的仍然返回…请确保我设置了@ComponentScan correctlyexclude仅适用于记录的自动配置。