我在春天很新,并且想知道使用注释时下面的配置是否是正确的方法。我注意到至少有两个问题:
<bean id= ...>...</bean>
来注入hibernate会话工厂,而不是使用注释你能提出你的建议吗? 谢谢
应用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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:tcp://localhost/~/test;IFEXISTS=TRUE" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.cupidocreative.hibernate.domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.connection.pool_size">10</prop>
<!-- <prop key="hibernate.show_sql">true</prop> -->
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
</props>
</property>
</bean>
<context:component-scan base-package="com.cupidocreative.hibernate.dao" />
<context:annotation-config />
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="postWorksheetDAO" class="com.cupidocreative.hibernate.dao.PostWorksheetDAO">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
PostWorksheetDAO.java
@Repository
@Transactional
public class PostWorksheetDAO {
@Autowired
private SessionFactory sessionFactory;
....hibernate operations
}
PostWorksheetService.java
@Service
public class PostWorksheetService {
@Autowired
private PostWorksheetDAO postWorksheetDAO;
public PostWorksheetDAO getPostWorksheetDAO() {
return postWorksheetDAO;
}
}
主类,始终返回null
public static void main(String[] args) {
//PostWorksheetService postWorksheetService = new PostWorksheetService();
// should use this
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
PostWorksheetService postWorksheetService = context.getBean(PostWorksheetService.class);
System.out.println(postWorksheetService.getPostWorksheetDAO());
System.out.println(postWorksheetService.getPostWorksheetDAO());
}