【问题标题】:wicket,spring jpa repository - nullpointer on @Autowirewicket,spring jpa 存储库-@Autowire 上的空指针
【发布时间】:2014-02-23 16:00:30
【问题描述】:

我正在尝试构建一个基于 wicket、Spring jpa 存储库和 Mysql 的应用程序。

问题是,我的服务类只是不想自动装配。如果我想使用我的自动装配类,我得到了一个空指针异常。

事实上,我得到了双空指针:我的 BaseServiceConfig.java 没有自动装配实现,并且 itnerface 中的自动装配存储库也是空的。所以,问题是为什么。

public final class ArmyBuilderPanel extends Panel {

@Autowired
DiskService diskService; //--> frist null, before setting it.

public ArmyBuilderPanel(String id) {
    super(id);
    add(new Label("armyPanel", "Content placeholder: Army builder panel"));
    diskService = new DiskServiceImpl();
    diskService.save(new Disk()); //--> second nullpointer
} }

我试图用最少甚至没有 xml 来做到这一点,所有的配置都是在 java 类中完成的。让我给你看代码:

存储库接口:

 @Transactional
 public interface DiskRepository extends JpaRepository<Disk, Long> {
 }

服务接口:

public interface DiskService {

public Disk save(Disk entity);

}

服务实施:

@Service 
public class DiskServiceImpl implements DiskService {

@Autowired
DiskRepository diskRepo;

@Override
public Disk save(Disk entity) {
    return diskRepo.save(entity);
}

}

BaseServiceConfig.java

@Configuration
@EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {

    @Bean
    DiskService diskService() {
        return new DiskServiceImpl();
    }

}

PersistenceJPAConfig.java

 @Configuration 
 @EnableTransactionManagement
 @EnableJpaRepositories(basePackages = {"hu.diskwars"}) public class
 PersistenceJPAConfig implements DisposableBean {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[]{"hu.diskwars"});

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/whdiskwars_db");
    dataSource.setUsername("Westy");
    dataSource.setPassword("pass");
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);
    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

Properties additionalProperties() {
    return new Properties() {
        {  // Hibernate Specific:
            setProperty("hibernate.hbm2ddl.auto", "create-drop");
            setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        }
    };
}

@Override
public void destroy() throws Exception {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} }

BaseServiceConfig.java(自动装配实现)

@Configuration @EnableJpaRepositories(basePackages = {"hu.diskwars"})
public class BaseServiceConfig {

@Bean
DiskService diskService() {
    return new DiskServiceImpl();
}

}

web.xml

> <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"
> xmlns="http://java.sun.com/xml/ns/javaee"
>   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_5.xsd">
> 
>   <display-name>diskwars</display-name>
>           <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>hu.diskwars.config</param-value>   </context-param>
> 
>   <listener>
>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
>   </listener>
>           <filter>        <filter-name>wicket.diskwars</filter-name>      <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
>       <init-param>            <param-name>applicationClassName</param-name>
>           <param-value>hu.diskwars.view.application.WicketApplication</param-value>
>       </init-param>   </filter>
> 
>   <filter-mapping>        <filter-name>wicket.diskwars</filter-name>
>       <url-pattern>/*</url-pattern>   </filter-mapping>   </web-app>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>hu.dwdb</groupId>
  <artifactId>diskwars</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>diskwars</name>
  <description></description>

  <properties>
      <wicket.version>6.13.0</wicket.version>
      <jetty.version>7.6.13.v20130916</jetty.version>
      <wtp.version>none</wtp.version>
                <slf4j.version>1.6.1</slf4j.version>
                <spring.version>3.2.2.RELEASE</spring.version>
                <jpa.version>1.2.0.RELEASE</jpa.version>
                <hibernate.version>4.2.0.Final</hibernate.version>
                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
          <type>jar</type>
      </dependency>

                <dependency>
                    <groupId>org.springframework.data</groupId>
                    <artifactId>spring-data-jpa</artifactId>
                    <version>${jpa.version}</version>
                    <type>jar</type>
                </dependency>

      <!--  WICKET DEPENDENCIES -->
      <dependency>
          <groupId>org.apache.wicket</groupId>
          <artifactId>wicket-core</artifactId>
          <version>${wicket.version}</version>
      </dependency>

      <dependency>
          <groupId>org.apache.wicket</groupId>
          <artifactId>wicket-extensions</artifactId>
          <version>${wicket.version}</version>
      </dependency>

      <!-- LOGGING DEPENDENCIES - LOG4J -->
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.6.4</version>
      </dependency>
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
      </dependency>

      <!--  JUNIT DEPENDENCY FOR TESTING -->
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
      </dependency>

      <!--  JETTY DEPENDENCIES FOR TESTING  -->
      <dependency>
          <groupId>org.eclipse.jetty.aggregate</groupId>
          <artifactId>jetty-all-server</artifactId>
          <version>${jetty.version}</version>
          <scope>provided</scope>
      </dependency>

                <!--  HIBERNATE DEPENDENCIES  -->
                <dependency>
                      <groupId>org.hibernate</groupId>
                      <artifactId>hibernate-core</artifactId>
                      <version>${hibernate.version}</version>
                </dependency>

                <dependency>
                      <groupId>org.hibernate</groupId>
                      <artifactId>hibernate-entitymanager</artifactId>
                       <version>${hibernate.version}</version>
                </dependency>

                 <!--  MYSQL DRIVER  -->
                <dependency>
                      <groupId>mysql</groupId>
                      <artifactId>mysql-connector-java</artifactId>
                      <version>5.1.29</version>
                </dependency>
  </dependencies>


  <build>
      <resources>
          <resource>
              <filtering>false</filtering>
              <directory>src/main/resources</directory>
          </resource>
          <resource>
              <filtering>false</filtering>
              <directory>src/main/java</directory>
              <includes>
                  <include>**</include>
              </includes>
              <excludes>
                  <exclude>**/*.java</exclude>
              </excludes>
          </resource>
      </resources>
      <testResources>
          <testResource>
              <filtering>false</filtering>
              <directory>src/test/resources</directory>
          </testResource>
          <testResource>
              <filtering>false</filtering>
              <directory>src/test/java</directory>
              <includes>
                  <include>**</include>
              </includes>
              <excludes>
                  <exclude>**/*.java</exclude>
              </excludes>
          </testResource>
      </testResources>

      <plugins>
          <plugin>
              <inherited>true</inherited>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.5.1</version>
              <configuration>
                  <source>1.6</source>
                  <target>1.6</target>
                  <encoding>UTF-8</encoding>
                  <showWarnings>true</showWarnings>
                  <showDeprecation>true</showDeprecation>
              </configuration>
          </plugin>

          <plugin>
              <groupId>org.mortbay.jetty</groupId>
              <artifactId>jetty-maven-plugin</artifactId>
              <version>${jetty.version}</version>
              <configuration>
                  <connectors>
                      <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
                          <port>8080</port>
                          <maxIdleTime>3600000</maxIdleTime>
                      </connector>
                      <connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
                          <port>8443</port>
                          <maxIdleTime>3600000</maxIdleTime>
                          <keystore>${project.build.directory}/test-classes/keystore</keystore>
                          <password>wicket</password>
                          <keyPassword>wicket</keyPassword>
                      </connector>
                  </connectors>
              </configuration>
          </plugin>

          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-eclipse-plugin</artifactId>
              <version>2.9</version>
              <configuration>
                  <downloadSources>true</downloadSources>
                  <wtpversion>${wtp.version}</wtpversion>
              </configuration>
          </plugin>
      </plugins>
  </build>

  <repositories>
      <repository>
          <id>Apache Nexus</id>
          <url>https://repository.apache.org/content/repositories/snapshots/</url>
          <releases>
              <enabled>false</enabled>
          </releases>
          <snapshots>
              <enabled>true</enabled>
          </snapshots>
      </repository>
  </repositories>
  </project>

这是我工作区的照片:

感谢您的帮助! http://i.stack.imgur.com/P32oV.png

编辑:

  • 将 SpringInjector 添加到我的基本检票口应用程序

    @覆盖 公共无效初始化(){ super.getComponentInstantiationListeners().add(new SpringComponentInjector(this)); }

  • 突然出现一个全新的错误,与我的持久性单元有关。

引起:org.springframework.beans.factory.BeanCreationException: 创建类中定义的名称为“entityManagerFactory”的bean时出错 路径资源 [hu/diskwars/config/PersistenceJPAConfig.class]: 调用 init 方法失败;嵌套异常是 java.lang.IllegalStateException:冲突的持久性单元 名称“diskwarsPU”的定义: 文件:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/, file:/D:/Development/projects/diskwars/target/diskwars-1.0-SNAPSHOT/WEB-INF/classes/

主要问题是,我什至没有persistance.xml 文件。我曾经(使用相同的确切名称“diskwarsPU”,但我把它扔掉了,当我知道时,我可以在没有它的情况下进行所有配置。 我清理,重新构建项目,甚至删除了目标文件夹,没有用。

【问题讨论】:

  • 看起来您尝试创建同一个 bean 两次。我猜是包裹扫描。

标签: spring hibernate web-applications wicket spring-data-jpa


【解决方案1】:

Wicket 对 Spring @Autowired 注释一无所知。使用 Wicket @SpringBean 注解和 SringComponentInjector 将 Sring bean 注入到 Wicket 组件中。

如何使用@SpringBean注解的完整示例有问题How can I get a Spring bean injected in my custom Wicket model class?

【讨论】:

  • 感谢您的回答,但我的服务类都没有被注入,这与检票口无关。 (DiskServiceImpl)。我猜,那里还有另一个错误,或者我只是不明白。
  • 请提供您的堆栈跟踪。
猜你喜欢
  • 2018-01-02
  • 2016-11-19
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 2016-07-31
相关资源
最近更新 更多