@Value不会注入属性,保持为空

时间:2017-02-27 10:59:19

标签: java spring servlets

我有一个servlet正在运行,我正在尝试将一个属性值注入Filter。

我确信正在加载appConfig文件(当我更改文件名时,我得到一个FileNotFound异常)。属性文件的计数相同。

我尝试注入属性的类似乎被Spring忽略了。它是一个过滤器(见下文)。我通过在注释本身中添加属性值来试验这个。 (@Value(" $ {filter.weburl:' some'}")。但是,String webURL仍为NULL。

任何人都可以帮我弄清楚这里发生了什么吗?

package example.servlet.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class AuthenticationFilter implements Filter{

    private ServletContext context;
    private final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
    @Value("${filter.weburl:'some'}")
    private String webURL;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.context = filterConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + " " + cookie.getValue() + "\n");
            }
        } else {
            ((HttpServletResponse)servletResponse).sendRedirect(webURL + "/inloggen");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

我的AppConfig文件:

package example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan("example")
@PropertySource("WEB-INF/service.properties")
public class AppConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public FilterRegistrationBean authenticationFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(getAuthenticationFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("authenticationFilter");
        filterRegistrationBean.setOrder(1);
        return null;
    }

    @Bean(name="authenticationFilter")
    public AuthenticationFilter getAuthenticationFilter() {
        return new AuthenticationFilter();
    }
}

3 个答案:

答案 0 :(得分:1)

您需要在配置类中使用以下内容。

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

要使用web.xml配置过滤器,请执行此操作

<filter>
    <filter-name>authenticationFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>authenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

答案 1 :(得分:1)

如果在应用程序上下文中注册过滤器,则会为所有请求注册过滤器,如果使用FilterRegistrationBean,则可以自定义过滤器适用的URL路径。你似乎有这两个,它可能会导致各种各样的问题。此外,您的过滤器使用@Component进行注释,并且您在配置类中将过滤器创建为bean。

这是您应该如何构建代码以使其工作:

// No @Component annotation keeps this class pure as you're using your configuration class to create beans
public class AuthenticationFilter implements Filter{

    private ServletContext context;
    private final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
    private String webURL;

    public AuthenticationFilter(String webURL) {
      this.webURL = webURL;
    }

    // rest of filter
}

配置类:

@Configuration
@ComponentScan("example") //if you have other components to scan, otherwise not required
@PropertySource("WEB-INF/service.properties")
public class AppConfig {

    @Value("${filter.weburl:some}")
    String webURL;

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

    @Bean
    public FilterRegistrationBean authenticationFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new AuthenticationFilter(this.webURL));
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("authenticationFilter");
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }
}

答案 2 :(得分:0)

有同样的问题,关于SE的所有答案都对我没有帮助。唯一有效的方法是用方法参数注入代替字段注入,即代替

@Configuration
public class MyConfig  {

    @Value("${jdbc.hibernate.dialect}") 
    private String dialect;
    @Value("${jdbc.hibernate.show_sql}") 
    private String showSql;

    @Bean
    public SessionFactory sessionFactory(DataSource dataSource) {
       ...
    }
}

使用了

@Configuration
public class MyConfig  {

    @Bean
    public SessionFactory sessionFactory(DataSource dataSource,
            @Value("${jdbc.hibernate.dialect}") String dialect,
            @Value("${jdbc.hibernate.show_sql}") String showSql) {
        ...
    }
}

请注意,在两种情况下,第一个参数(数据源)均已正确注入,只有属性未正确插入。