Добавление ContextListener в полную конфигурацию Spring на основе Java - PullRequest
0 голосов
/ 20 января 2019

Я пытаюсь настроить конфигурацию Spring на основе класса Java @Configuration и файла web.xml.Я определил две разные конфигурации: KatherineConfig.java, которая содержит конфигурацию уровня JPA;KatherineWebConfig.java, который импортирует первый файл конфигурации и добавляет отображение сервлета в конфигурацию Spring.

Теперь я хотел бы добавить ContextLoaderListener в мою конфигурацию.Я понятия не имею, как это сделать.

Это моя конфигурация web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.3"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_3.xsd">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>it.manuelgozzi.katherine.web.configuration.KatherineWebConfig
        </param-value>
    </context-param>

    <display-name>Katherine</display-name>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Это мой KatherineWebConfig.java файл:

package it.manuelgozzi.katherine.web.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import it.manuelgozzi.katherine.finance.configuration.KatherineConfig;

@Configuration
@Import(KatherineConfig.class)
@ComponentScan(basePackages = { "it.manuelgozzi.katherine.web" })
@EnableWebMvc
public class KatherineWebConfig {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

И, наконец, это KatherineConfig.java файл:

package it.manuelgozzi.katherine.finance.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
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.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * Configurazione di Katherine. I parametri sono gestiti esternamente mediante
 * il file katherine.configuration.properties.
 * 
 * @author Manuel Gozzi
 * @date Jan 6, 2019
 * @time 6:12:48 PM
 */
@Configuration
@ComponentScan(basePackages = {"it.manuelgozzi.katherine.finance", "it.manuelgozzi.katherine.web"})
@EnableJpaRepositories(basePackages = "it.manuelgozzi.katherine.finance.model.entity.repository")
@PropertySource("classpath:katherine.configuration.properties")
public class KatherineConfig {

    @Value("${datasource.username}")
    private String dataSourceUsername;

    @Value("${datasource.password}")
    private String dataSourcePassword;

    @Value("${datasource.url}")
    private String dataSourceUrl;

    @Value("${datasource.driverclassname}")
    private String dataSourceDriverClassName;

    @Value("${entitymanager.packagestoscan}")
    private String entityManagerPackagesToScan;

    /**
     * Configurazione del bean relativo al datasource.
     * 
     * @author Manuel Gozzi
     * @date Jan 6, 2019
     * @time 6:13:01 PM
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername(dataSourceUsername);
        dataSource.setPassword(dataSourcePassword);
        dataSource.setUrl(dataSourceUrl);
        dataSource.setDriverClassName(dataSourceDriverClassName);
        return dataSource;
    }

    /**
     * Configurazione del TransactionManager.
     * 
     * @author Manuel Gozzi
     * @date Jan 6, 2019
     * @time 6:13:12 PM
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

    /**
     * Configurazione dell'EntityManagerFactory.
     * 
     * @author Manuel Gozzi
     * @date Jan 6, 2019
     * @time 6:13:24 PM
     * @return
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { entityManagerPackagesToScan });
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        return em;
    }

}

Не могли бы вы объяснить, как реализовать это решение?Моя цель - встать на ноги вместе с настройкой Java и web.xml.

Я пытаюсь запустить свое приложение как есть, но получаю следующее исключение:

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

Спасибов совет!

РЕДАКТИРОВАТЬ:

Я создал класс, который реализует WebApplicationInitializer таким образом:

package it.manuelgozzi.katherine.web.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import it.manuelgozzi.katherine.finance.configuration.KatherineConfig;

public class KatherineWebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext annotationConfigContext = new AnnotationConfigWebApplicationContext();
        annotationConfigContext.register(KatherineWebConfig.class);
        annotationConfigContext.register(KatherineConfig.class);
        servletContext.addListener(new ContextLoaderListener(annotationConfigContext));
    }

}

Теперь яполучить следующее исключение:

java.lang.IllegalArgumentException: ResourceLoader must not be null!

Что мне не хватает?

1 Ответ

0 голосов
/ 20 января 2019

Вам необходимо добавить свой класс конфигурации AnnotationConfigWebApplicationContext :

 context = new AnnotationConfigWebApplicationContext();
 context.register(KatherineConfig.class);

Реализация WebApplicationContext, которая принимает аннотированные классы в качестве входных данных - в частности @ аннотированные классами конфигурации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...