Spring MVC @ Value / @ ConfigurationProperties在MainConfig上工作但在SecurityConfig上没有

问题描述 投票:1回答:3

我有一个简单的Spring MVC 5项目,启用了安全层。除了属性加载之外,一切都很好,仅在安全配置上。我告诉你这个场景,你可以看到它。

application.properties(位于src / main / resources)

com.company.myapp.prop=myprop

main config.Java

@Configuration
public class MainConfig implements WebMvcConfigurer {

    @Value("${com.company.myapp.prop}")
    private String prop;

    @Bean
    public MySpecialBean mySpecialBean() {
        System.out.println(prop); // output > myprop
        return new MySpecialBean();
    }
}

security config.Java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${com.company.myapp.prop}")
    private String prop;

    @Bean
    public MySpecialSecurityBean mySpecialSecurityBean() {
        System.out.println(prop); // output > null
        return new MySpecialSecurityBean();
    }
}

我不明白为什么会这样。我已经将@EnableWebSecurity注释切换到app类,尝试自己设置PropertySourcesPlaceholderConfigurer,但没有任何效果。你知道发生了什么吗?

spring spring-mvc spring-security properties autowired
3个回答
0
投票

来自@PropertySource的官方文档:

在<bean>和@Value注释中解析$ {...}占位符

为了使用PropertySource中的属性解析定义或@Value注释中的$ {...}占位符,必须确保在ApplicationContext使用的BeanFactory中注册了适当的嵌入值解析器。在XML中使用时会自动发生这种情况。使用@Configuration类时,可以通过静态@Bean方法显式注册PropertySourcesPlaceholderConfigurer来实现。但请注意,通常只有在需要自定义配置(如占位符语法等)时才需要通过静态@Bean方法显式注册PropertySourcesPlaceholderConfigurer。请参阅@Configuration的javadocs中的“使用外部化值”部分和“a关于详细信息和示例,请注意@ Bean的javadocs的BeanFactoryPostProcessor-返回@Bean方法。

您应该尝试将注释@PropertySource添加到配置类中。

@Configuration
@PropertySource("classpath:my.properties")
public class MainConfig implements WebMvcConfigurer {}

然后尝试在SecurityConfig类中访问您的属性

要获得完整信息,请参阅official docs

我希望它会对你有所帮助


0
投票

这适合我。我猜你有另一个触发应用程序的类,并使用@SpringBootApplication进行注释另外,你的方法mySpecialBean不返回MySpecialBean实例,所以这可能甚至都没有编译。你还在使用其他课程吗?请指教


0
投票

终于明白了!该问题与一些依赖关系优先级和不必要的bean声明有关。进入细节,我正在使用OAuht2,我开始使用this tutorial。最后我也和this one混在一起(最近)。这个问题与那些不需要声明为bean的@ Bean相关:

  • ClientRegistrationRepository
  • ClientRegistration
  • OAuth2AuthorizedClientService

Spring在任何其他配置之前调用这些bean,因此尚未加载任何属性。也许更改优先级,依赖性甚至订单都可以解决问题,但是当我分析代码时,我发现这些方法仅用于安全配置,而不是应用程序的任何其他部分。所以我删除了@Bean声明,现在一切正常!在安全配置中调用这些方法时,属性已经加载。

希望能帮助那里的人。

© www.soinside.com 2019 - 2024. All rights reserved.