春季控制器:如何使用属性$ {..}在@RequestMapping?(Spring control

2019-09-29 19:50发布

我已经发现了一些问题与答案,但他们不帮我。

我有,我用一个春天控制器(4.2.5)和Spring安全(4.0.2)的Web servlet的项目。 我不使用Spring启动。

我的项目工作正常。

但现在我的任务是这样的:
@RequestMapping(value={"auth/**"}配置 (更换"auth/**"${dm.filterPattern}

问题:在@RequestMapping ${dm.filterPattern}没有解决,虽然@PropertySource处理。

这是入门dm.filterPattern在dmConfig.properties:

dm.filterPattern=/auth/*

下面是一些必要的代码,所有的Spring注解。

控制器:

该方法的输出init()表示我@PropertySource被正确处理。 env.getProperty("...")返回正确的值。

@Controller
@PropertySource("classpath:/dmConfig.properties")
@RequestMapping(value ={ "${dm.filterPattern}"})
public class DmProxyController implements ApplicationContextAware
{
    private Environment env;

    @Autowired
    public DmProxyController(Environment env)
    {
        this.env = env;
    }

    @RequestMapping(path={"${dm.filterPattern}"} ,method = RequestMethod.POST)
    protected void doPost(HttpServletRequest customerRequest, HttpServletResponse response)
            throws ServletException, IOException, DmException
    {
           // code for POST request
    }

    @RequestMapping(path={"${dm.filterPattern}"} ,method = RequestMethod.GET)
    protected void doGet(HttpServletRequest customerRequest, HttpServletResponse response)
            throws ServletException, IOException, DmException
    {
           // code for GET request
    }

    @PostConstruct
    public void init() throws ServletException
    {
        RequestMappingHandlerMapping requestMapping=
                (RequestMappingHandlerMapping) appContext.getBean("requestMappingHandlerMapping");

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMapping.getHandlerMethods();
        logger.debug("RequestMapping via dm.filterPattern: {}",
                env.getProperty("dm.filterPattern"));
                logger.debug("Handler Methods: {}", handlerMethods.size());

        for (RequestMappingInfo mapInfo : handlerMethods.keySet())
        {
            logger.debug(" Mappinginfo: {} --> {}", mapInfo, handlerMethods.get(mapInfo));
        }
    }
}

与bean定义类

@Configuration
@PropertySource("classpath:/dmConfig.properties")
@ComponentScan(basePackages = "com.dm.filter, com.dm.controller")
@EnableTransactionManagement(mode = AdviceMode.PROXY, proxyTargetClass = false)
@Import({DmSecurityConfigurer.class, DmWebConfigurer.class})
public class DmRoot
{

}

DispatcherServletInitializer

public class DmDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    @Override
    protected Class<?>[] getRootConfigClasses()
    { return new Class[]{DmRoot.class};  }

    @Override
    protected Class<?>[] getServletConfigClasses()
    { return null; }

    @Override
    protected String[] getServletMappings()
    { return new String[]{"/"}; }

    @Override
    protected String getServletName()
    {  return "dmDispatcherServlet";  }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration)
    {
        super.customizeRegistration(registration);
        registration.setLoadOnStartup(1);
    }
}

WebConfigurer

public class DmWebConfigurer extends WebMvcConfigurerAdapter
{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/index.html").addResourceLocations("/");
        registry.setOrder(Integer.MAX_VALUE-5);
    }
}

SecurityWebApplicationInitializer

public class DmSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{
    public DmSecurityWebApplicationInitializer()
    {
        // some logging
    }

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext)
    {     // adding own filters   }

    @Override
    protected void afterSpringSecurityFilterChain(ServletContext servletContext)
    {     // adding own filters   }
}

SecurityConfigurer

@EnableWebMvc
@EnableWebSecurity
@PropertySource("classpath:dmConfig.properties")
public class DmSecurityConfigurer extends WebSecurityConfigurerAdapter
{

    private static Logger logger = LogManager.getLogger(DmSecurityConfigurer.class.getName());

    @Autowired
    private Environment env;

    @Autowired
    private UserDetailsService dmUserDetailsService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        String urlPattern = env.getProperty("dm.springSecurityPattern");
        String realmName = env.getProperty("dm.springSecurityRealm");

        httpSecurity.httpBasic().realmName(realmName)
                .and().userDetailsService(dmUserDetailsService)
                .authorizeRequests()
                .antMatchers(urlPattern).authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
    }

}

Answer 1:

有一种可能性,即PropertySourcesPlaceholderConfigurer被比你的控制器,因此该值不解决Spring上下文后初始化。 尝试添加显式bean定义PropertySourcesPlaceholderConfigurer在如下根配置文件中的一个;

@PropertySource("classpath:/dmConfig.properties")
public class DmWebConfigurer extends WebMvcConfigurerAdapter
{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/index.html").addResourceLocations("/");
        registry.setOrder(Integer.MAX_VALUE-5);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

究其原因,你可以看到在正确的价值观init()方法是因为所有的豆子被初始化,包括之后它被称为PropertySourcesPlaceholderConfigurer



文章来源: Spring controller: How to use property ${..} in @RequestMapping?