0

Добрый день! Есть web-приложение. 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;

Так можно СОЗДАТЬ контекст в классе(не бине):

private ApplicationContext context =
        new AnnotationConfigApplicationContext(AppConfig.class,     HibernateConfiguration.class, MyAppConfigForAsync.class);

Подскажите пожалуйста как получить уже созданный при запуске сервера приложений Spring-контекст в объекте класса, который не является бином ?

1 ответ 1

4

Можно создать spring-компонент, в который заинжектится spring-контекст в статическую переменную:

@Component
public class ApplicationContextHolder {

    // Контекст Spring
    private static ApplicationContext ctx;

    @Autowired
    public ApplicationContextHolder(ApplicationContext applicationContext) {
        ApplicationContextHolder.ctx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
}

Затем используйте в другом классе:

public class NotBean {
    private final ApplicationContext ctx;

    public NotBean() {
        ctx = ApplicationContextHolder.getApplicationContext();
    }
}

Update - вариант с использованием ApplicationContextAware

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    // Контекст Spring
    private static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.ctx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
}
1
  • Спасибо, то что надо.
    – Adrenal1ne
    29 авг 2017 в 7:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.