下午好!有一个网络应用程序。AppConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.package")
@EnableJpaRepositories("net.package.repository")
public class AppConfig extends WebMvcConfigurerAdapter{
@Autowired
RoleToUserProfileConverter roleToUserProfileConverter;
@Bean(name = "applicationContextProvder")
public ApplicationContextProvider getApplicationContextProvider() {
return new ApplicationContextProvider();
}
@Bean(name="multipartResolver")
public CommonsMultipartResolver getResolver() throws IOException {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
//Set the maximum allowed size (in bytes) for each individual file.
resolver.setMaxUploadSizePerFile(5242880);//5MB
//You may also set other available properties.
return resolver;
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/favicon.ico"). addResourceLocations("/favicon.ico");
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(roleToUserProfileConverter);
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseRegisteredSuffixPatternMatch(true);
}
通常可以像这样获得上下文:
@Autowired
private ApplicationContext ctx;
所以你可以在一个类(不是一个bean)中创建一个上下文:
private ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class, HibernateConfiguration.class, MyAppConfigForAsync.class);
你能告诉我如何在一个不是 bean 的类对象中获取在应用程序服务器启动时已经创建的 Spring 上下文吗?
您可以创建一个将 spring 上下文注入静态变量的 spring bean:
然后在另一个类中使用:
更新- 使用ApplicationContextAware的变体