我有一個servlet正在運行,我正在嘗試將一個屬性值注入到Filter中。@Value不注入屬性,保持爲null
我相信appConfig文件正在被加載(當我改變文件名時,我得到一個FileNotFound異常)。屬性文件的計數相同。
似乎我嘗試注入屬性的類在某種程度上被Spring忽略了。這是一個過濾器(見下文)。我已經通過在註釋本身中添加屬性值來進行試驗。 (@Value( 「$ {filter.weburl: '一些'}」。)但是,字符串WEBURL保持爲空
誰能幫助我弄清楚是怎麼回事
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();
}
}
你的過濾器其實也是一個Spring bean?基本上,如果該字段無法解析,則該字段不能爲空,它將回退到您提供的默認值。由於事實並非如此,我懷疑你使用的過濾器的實例是Spring所知的一個實例。 –
您是否嘗試過設置應該由@Value填充到公共的字段? –