我正在尝试使用@Value
时遇到此问题@Value("${message}")
private String message;
因此,在我使用@Controller注释和
的类中,字符串消息得到了愉快的解决@RequestMapping(value = "{locale}/sandbox", method = RequestMethod.GET)
但是,当我在从JSP页面调用的类中使用时,它无法解析。我没有使用任何XML,如application-context / servlet.context.xml等。而不是我正在使用WebAppInitializer
@Slf4j
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
servletAppContext.register(SpringInitializer.class);
registerListener(servletContext, new ContextLoaderListener(servletAppContext));
registerServlet(servletContext, new DispatcherServlet(servletAppContext), "/").setLoadOnStartup(1);
}
此外,我已经定义了这个bean来读取属性文件
@Configuration
public class DevPropertyReader {
@Bean
public static PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] { new ClassPathResource("properties/application-dev.properties") };
ppc.setLocations(resources);
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}
在阅读了几篇文章之后,我发现应该在servlet-context和dispatcher-servlet中定义属性占位符。不确定这是否是解决方案,但如果是,那么如何在WebAppInitializer中实现它,并且@Bean与@Component不应该在任何地方都可用吗?
答案 0 :(得分:0)
管理最终解决问题。因此根本原因是我试图访问非Spring托管bean
所以要解决这个问题,我必须做的是使用@Service注释注释我的类,然后使用以下代码获取spring托管bean的实例,而不是通过jsp创建一个新的bean
<%@ page import="com.belmond.utils.ProductDataModel"%>
<%@ page import="org.springframework.web.servlet.support.RequestContextUtils"%>
<%@ page import="org.springframework.context.ApplicationContext"%>
<%
ApplicationContext context =
RequestContextUtils.getWebApplicationContext(request);
ProductDataModel productData = (ProductDataModel)context.getBean("productDataModel");
//Where ProductDataModel is the class whose bean I wanted
%>
现在使用@value注释的$ {message}正在解决
@Slf4j
@Service
public class ProductDataModel {
@Value("${message}")
private String message;