gpt4 book ai didi

java - autowire 不适用于基于 jpa tomcat 和 jersey xml

转载 作者:行者123 更新时间:2023-11-28 23:47:17 25 4
gpt4 key购买 nike

我现在卡住了。

首先,我制作了从控制台运行的 Java 应用程序,并且是基于注释的配置。
以下配置在从控制台运行时有效配置在配置包中

@Configuration
public class JpaConfiguration {

@Value("#{dataSource}")
private javax.sql.DataSource dataSource;


@Bean
public Map<String, Object> jpaProperties() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("hibernate.dialect", MySQL5Dialect.class.getName());
props.put("javax.persistence.validation.factory", validator());
props.put("hibernate.ejb.naming_strategy", ImprovedNamingStrategy.class.getName());
return props;
}

@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
hibernateJpaVendorAdapter.setShowSql(false);
return hibernateJpaVendorAdapter;
}

@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(
localContainerEntityManagerFactoryBean().getObject());
}

@Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(this.dataSource);
lef.setPackagesToScan("domain");
lef.setJpaPropertyMap(this.jpaProperties());
lef.setJpaVendorAdapter(this.jpaVendorAdapter());
return lef;
}
}

@Configuration
@ImportResource("classpath:root-context.xml")
@PropertySource("classpath:database.properties")
public class DataSourceConfig {

public DataSourceConfig() {}

}

这是我在 src/main/resources 包中的 root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<context:property-placeholder location="classpath:database.properties" />

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}"
p:initialPoolSize="0"
p:minPoolSize="0"
p:maxPoolSize="10"
p:maxIdleTime="300" />

<jpa:repositories base-package="domain" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

我的主要方法

public class ConsoleRun {

public static void main(String[] args) throws Exception {

final Logger log = LoggerFactory
.getLogger("ConsoleRun");

log.info("Starting application");

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("*");
ctx.refresh();

TestDao testDao = ctx.getBean(TestDao.class);
testDao.testUsersList();

log.info("========GETTING ALL RESULTS==============");
testDao.testResultsList();
}
}

我的用于访问位于控制台包中的 DAO 的服务类

@Service
public class TestDao {

static final Logger log = LoggerFactory.getLogger("TestDatabase");

@Autowired
private UserDao userDao;

@Autowired
private ResultDao resultDao;

@Autowired
private GameDao gameDao;

public List<User> testUsersList() {
log.info("Getting all users");
List<User> users = userDao.findAll();
for (User u : users) {
log.info("User: {}", u);
}
return users;
}


public void testResultsList() {
List<Result> results = resultDao.findAll();
for (Result r : results) {
log.info("Result: {}", r);
}
}

public User findUserById(Long id) {
return userDao.findById(id);
}
}

以上代码在从控制台启动时有效

下面的代码不起作用

现在我想在 Tomcat 容器中运行它时遇到问题。我正在尝试不同的方式来配置它。
我如何为 Tomcat 重用我的 JpaConfiguration 类和 root-context.xml?

这是我目前在我的 web.xml 中的内容

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</context-param>

<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>

我的 app-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<jpa:repositories base-package="domain" />
<context:component-scan base-package="domain,api,config" />

<!-- Weaves in transactional advice around @Transactional methods -->
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="dataSource" class="config.DataSourceConfig" />
<bean id="JpaConfiguration" class="config.DataSourceConfig" />

</beans>

这里是userDao没有 Autowiring 并抛出空指针异常的主要问题 Authresource在api包中

@Component
@Path("/auth")
public class AuthResource {

@Autowired
UserDao userDao;

@Autowired
TestDao testDao;

@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public List<User> getAllUsers() {

return userDao.findAll();
}
}

我的休息工作,我有简单的 REST 服务类,适用于 url localhost:8080/application/rest/hello/message

@Path("/hello")
public class HelloResource {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {

String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}

tomcat 是否可以直接从 java 配置文件加载配置?这就是我在 app-config.xml <context:component-scan base-package="domain,api,config" /> 中的内容还有什么地方可能是问题以及为什么我在 AuthResource 类中得到 userDao 的空指针异常?

最佳答案

我认为您需要将 ContextLoaderListener 添加到您的 web.xml

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

关于java - autowire 不适用于基于 jpa tomcat 和 jersey xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12762209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com