I'm very new in spring, and wonder if configurations below is a correct approach when using annotation. I notice at least 2 problems :
- In application-context.xml, I still have to configure bean
<bean id= ...>...</bean>
to inject hibernate session factory, instead of using annotation - Sample codes below always returns null on main()
Can you give your suggestion? Thank you
application-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;
}
}
Main class, always returns 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());
}