我使用Jersey,Spring Boot和Spring Data创建一个REST服务。
我的设置是Java 1.8,Maven 3.3.9,Spring Framework 4.3.0.RELEASE,Jersey 2.23.1,Spring Boot 1.3.6.RELEASE,javax.ws.rs-api 2.0.1, Hibernate 5.1.0.FINAL
我尝试通过在context.xml
中定义数据源并在application.properties
中引用它来构建数据源。请参阅方法permDbJpaDataSource()
。
但似乎忽略了条目spring.datasource.jndi-name=jdbc/permDb
。创建了一个名为permDbJpaDataSourceFAIL
的bean,但是
所有属性都为null(数据库URL,数据库用户等...)。我可以看到文件application.properties
被评估,因为
spring.main.banner-mode=off
。
方法jndiDataSource()
工作正常,我可以用这种方式构建我的应用程序。但我想知道我是否做错了什么
或者如果它是一个错误。
这些是我的来源:
├───java
│ └───com
│ └───pkg
│ └───permDb
│ └───service
│ │ PermDbServiceApplication.java
│ │
│ ├───services
│ │ PermDbOwsService.java
│ │
│ └───springBoot
│ PermDbJerseyConfig.java
│ PermDbServiceSpringBoot.java
│
├───resources
│ │ application.properties
│ │ log4j2.xml
│ │
│ └───META-INF
│ context.xml
│
└───webapp
PermDbServiceApplication.java
package com.pkg.permDb.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class PermDbServiceApplication extends SpringBootServletInitializer
{
//private static Logger logger = LogManager.getLogger(PermDbServiceApplication.class.getName());
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(PermDbServiceApplication.class);
}
public static void main(String[] args)
{
SpringApplication.run(PermDbServiceApplication.class, args);
}
}
PermDbServiceSpringBoot.java
package com.pkg.permDb.service.springBoot;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.NamingException;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.*;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement(mode = AdviceMode.PROXY, proxyTargetClass = false)
@ComponentScan(basePackages = "com.pkg.permDb.repositories")
public class PermDbServiceSpringBoot
{
private static Logger logger = LogManager.getLogger(PermDbServiceSpringBoot.class.getName());
@Bean(name = "permDbEntityManager")
public LocalContainerEntityManagerFactoryBean permDbEntityManagerFactoryBean() throws
IOException
{
//Properties dmProps = dmProperties();
Map<String, Object> propsMap = new Hashtable<>();
logger.debug("erzeuge Bean {} ...", LocalContainerEntityManagerFactoryBean.class.getName());
logger.debug("DataSource: {}", jndiDataSource());
//propsMap.put("javax.persistence.schema-generation.database.action",
// dmProps.getProperty("dm.hibernateDbSchemaGeneration"));
HibernateJpaVendorAdapter hibAdapter = new HibernateJpaVendorAdapter();
//hibAdapter.setDatabasePlatform(dmProps.getProperty("dm.hibernateDbDialect"));
hibAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQL9Dialect");
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(hibAdapter);
factoryBean.setDataSource(jndiDataSource());
//factoryBean.setPackagesToScan(dmProps.getProperty("dm.userDbModel"));
factoryBean.setPackagesToScan("com.pkg.permDb.entities");
factoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factoryBean.setValidationMode(ValidationMode.NONE);
factoryBean.setPersistenceUnitName("PermDb");
factoryBean.setJpaPropertyMap(propsMap);
logger.debug("Bean erzeugt: {}", factoryBean);
return factoryBean;
}
@Bean(name = "permDbJpaDataSource")
public DataSource permDbJpaDataSource() throws DataSourceLookupFailureException, IOException
{
/* ##############################
when these lines are executed, the entry spring.datasource.jndi-name
from application.properties is not evaluated
############################## */
logger.debug("erzeuge Bean {} ...", DataSource.class.getName());
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
String dataSourceName = "java:comp/env/jdbc/permDb";
DataSource dataSource = lookup.getDataSource(dataSourceName);
logger.debug("Bean erzeugt: {}", dataSource);
return dataSource;
}
@Bean(name ="permDbJpaDataSourceFAIL")
public DataSource jndiDataSource()
{
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/permDb");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
try
{
bean.afterPropertiesSet();
}
catch (NamingException e)
{
logger.error("FEHLER: ", e);
}
return (DataSource) bean.getObject();
}
@Bean(name = "permDbTransactionManager")
//@Bean
public PlatformTransactionManager transactionManager() throws IOException
{
return new JpaTransactionManager(permDbEntityManagerFactoryBean().getObject());
}
}
PermDbJerseyConfig.java
package com.pkg.permDb.service.springBoot;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
import com.pkg.permDb.service.services.PermDbOwsService;
@Component
public class PermDbJerseyConfig extends ResourceConfig
{
private static Logger logger = LogManager.getLogger(PermDbJerseyConfig.class.getName());
public PermDbJerseyConfig()
{
logger.debug("register services");
register(PermDbOwsService.class);
}
}
application.properties
spring.datasource.jndi-name=jdbc/permDb
spring.datasource.driver-class-name=org.postgresql.Driver
spring.main.banner-mode=off
#spring.jmx.enabled=false
context.xml中
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/permDb" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://my.server.de:5432/oaktree"
username="uhtred" password="password" maxTotal="50" maxIdle="10"
maxWaitMillis="-1"/>
</Context>
模块permDbService的pom.xml ,父请参见下文
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>permDb</artifactId>
<groupId>com.permDb</groupId>
<version>0.2.2-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>permDbService</artifactId>
<version>0.1.2-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jersey.version>2.23.1</jersey.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.permDb</groupId>
<artifactId>permDbRepositories</artifactId>
<version>0.1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!--<version>9.4.1208</version>-->
</dependency>
<!-- ################### LOGGING ####################-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<!--
<dependency>
<!– dies wird benötigt, damit das Hibernate-Logging über log4j2 konfigurierbar ist–>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
-->
<dependency>
<groupId>org.apache.logging.log4j.adapters</groupId>
<artifactId>log4j-1.2-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
</project>
父pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.permDb</groupId>
<artifactId>permDb</artifactId>
<packaging>pom</packaging>
<version>0.2.2-SNAPSHOT</version>
<parent>
<groupId>com</groupId>
<artifactId>mavenToolParent</artifactId>
<version>1.0.0</version>
</parent>
<modules>
<module>permDbData</module>
<module>permDbService</module>
<module>permDbRepositories</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- zum timestamp siehe http://rterp.wordpress.com/2012/03/16/stamping-version-number-and-build-time-in-properties-file-with-maven/ -->
<build.timestamp>${maven.build.timestamp}</build.timestamp>
<maven.build.timestamp.format>dd.MM.yyyy HH:mm</maven.build.timestamp.format>
<log4j.version>2.6.1</log4j.version>
<hibernate.version>5.1.0.Final</hibernate.version>
<spring.version>4.3.0.RELEASE</spring.version>
</properties>
<profiles>
<profile>
<id>permDb-local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
</properties>
</profile>
<profile>
<id>permDb-ref</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
</properties>
</profile>
</profiles>
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>META-INF/context.xml</exclude>
</excludes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<!--<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>-->
<webResources>
<resource>
<directory>src/main/webapp</directory>
<includes>
<include>**/*.html</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/META-INF</directory>
<targetPath>/META-INF</targetPath>
<includes>
<include>context.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<id>enforce-maven-3</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>3.3.9</version>
</requireMavenVersion>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j.adapters</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<!-- dies wird benötigt, damit das Hibernate-Logging über log4j2 konfigurierbar ist-->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1208</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>com.ows</groupId>
<artifactId>owsMisc</artifactId>
<version>1.0.0</version>
</dependency>
<!-- ################# TEST ################# -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
UPDTAE
这是我开始申请时的输出:
2016-07-28 11:31:03.802 INFO 5636 --- [on(3)-127.0.0.1] d.lgn.permDb.service.PermDbServiceApplication : Starting PermDbServiceApplication on GLL-H3-W7P139 with PID 5636 (D:\catalina-base-idea\webapps\permDb\WEB-INF\classes\com\pkg\permDb\service\PermDbServiceApplication.class started by ulrich.knaack in D:\Programme\apache-tomcat-8.0.15\bin)
2016-07-28 11:31:03.818 INFO 5636 --- [on(3)-127.0.0.1] d.lgn.permDb.service.PermDbServiceApplication : No active profile set, falling back to default profiles: default
2016-07-28 11:31:03.880 INFO 5636 --- [on(3)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@410bf06: startup date [Thu Jul 28 11:31:03 CEST 2016]; root of context hierarchy
2016-07-28 11:31:05.175 INFO 5636 --- [on(3)-127.0.0.1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-07-28 11:31:05.284 INFO 5636 --- [on(3)-127.0.0.1] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fbaaf65b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-07-28 11:31:05.331 INFO 5636 --- [on(3)-127.0.0.1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1451 ms
11:31:05.627 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbJerseyConfig - register services
2016-07-28 11:31:05.830 INFO 5636 --- [on(3)-127.0.0.1] b.a.w.TomcatWebSocketContainerCustomizer : NonEmbeddedServletContainerFactory detected. Websockets support should be native so this normally is not a problem.
2016-07-28 11:31:05.861 INFO 5636 --- [on(3)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2016-07-28 11:31:05.861 INFO 5636 --- [on(3)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-07-28 11:31:05.861 INFO 5636 --- [on(3)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-07-28 11:31:05.861 INFO 5636 --- [on(3)-127.0.0.1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'com.pkg.permDb.service.springBoot.PermDbJerseyConfig' to [/*]
11:31:05.877 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbServiceSpringBoot - erzeuge Bean org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean ...
11:31:05.877 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbServiceSpringBoot - erzeuge Bean javax.sql.DataSource ...
11:31:05.877 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbServiceSpringBoot - Bean erzeugt: org.apache.tomcat.dbcp.dbcp2.BasicDataSource@49f798a4
11:31:05.986 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbServiceSpringBoot - DataSource: org.apache.tomcat.dbcp.dbcp2.BasicDataSource@49f798a4
11:31:06.017 [RMI TCP Connection(3)-127.0.0.1] DEBUG PermDbServiceSpringBoot - Bean erzeugt: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@439cc9b9
2016-07-28 11:31:06.033 INFO 5636 --- [on(3)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'PermDb'
2016-07-28 11:31:06.049 INFO 5636 --- [on(3)-127.0.0.1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: PermDb
...]
2016-07-28 11:31:06.205 INFO 5636 --- [on(3)-127.0.0.1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.11.Final}
2016-07-28 11:31:06.205 INFO 5636 --- [on(3)-127.0.0.1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-07-28 11:31:06.205 INFO 5636 --- [on(3)-127.0.0.1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-07-28 11:31:06.501 INFO 5636 --- [on(3)-127.0.0.1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-07-28 11:31:06.891 INFO 5636 --- [on(3)-127.0.0.1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2016-07-28 11:31:06.906 INFO 5636 --- [on(3)-127.0.0.1] o.h.e.jdbc.internal.LobCreatorBuilder : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2016-07-28 11:31:07.187 INFO 5636 --- [on(3)-127.0.0.1] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-07-28 11:31:08.388 INFO 5636 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-07-28 11:31:08.404 INFO 5636 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'permDbJpaDataSource' has been autodetected for JMX exposure
2016-07-28 11:31:08.404 INFO 5636 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'permDbJpaDataSource': registering with JMX server as MBean [org.apache.tomcat.dbcp.dbcp2:name=permDbJpaDataSource,type=BasicDataSource]
2016-07-28 11:31:08.420 ERROR 5636 --- [on(3)-127.0.0.1] o.s.boot.SpringApplication : Application startup failed
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@49f798a4] with key 'permDbJpaDataSource'; nested exception is javax.management.InstanceAlreadyExistsException: Catalina:type=DataSource,host=localhost,context=/permDb,class=javax.sql.DataSource,name="jdbc/permDb"
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:625) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:550) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:432) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]