Java本地应用 使用spring 注解初始化

96 篇文章 0 订阅

service 类 及 接口 

ISample.Java

  1. /** 
  2.  *  
  3.  */  
  4. package test;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. /**  
  10.  * @ClassName: Test  
  11.  * @Description: TODO(这里用一句话描述这个类的作用)  
  12.  * @author zhoushun  
  13.  * @date 2012-12-12 上午10:13:51  
  14.  *   
  15.  */  
  16. public class Test {  
  17.     public static void main(String[] args){  
  18.         ApplicationContext applicationContext = null;    
  19.         String[] fileUrl = new String[]{"classpath*:*Context*.xml"};    
  20.         applicationContext = new ClassPathXmlApplicationContext(fileUrl);    
  21.         //applicationContext = new FileSystemXmlApplicationContext(fileUrl);   
  22.         ISample s = (ISample)SpringBeanUtil.getBean("sampleService");  
  23.         s.test();  
  24.     }  
  25. }  
/**
 * 
 */
package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/** 
 * @ClassName: Test 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author zhoushun 
 * @date 2012-12-12 上午10:13:51 
 *  
 */
public class Test {
	public static void main(String[] args){
		ApplicationContext applicationContext = null;  
		String[] fileUrl = new String[]{"classpath*:*Context*.xml"};  
		applicationContext = new ClassPathXmlApplicationContext(fileUrl);  
		//applicationContext = new FileSystemXmlApplicationContext(fileUrl); 
		ISample s = (ISample)SpringBeanUtil.getBean("sampleService");
		s.test();
	}
}

SampleService.java

  1. /** 
  2.  *  
  3.  */  
  4. package test;  
  5.   
  6. import java.util.List;  
  7.   
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.beans.factory.annotation.Qualifier;  
  10. import org.springframework.context.annotation.Scope;  
  11. import org.springframework.orm.hibernate3.HibernateTemplate;  
  12. import org.springframework.stereotype.Service;  
  13. import org.springframework.transaction.annotation.Propagation;  
  14. import org.springframework.transaction.annotation.Transactional;  
  15.   
  16. /**  
  17.  * @ClassName: SampleService  
  18.  * @Description: TODO(这里用一句话描述这个类的作用)  
  19.  * @author zhoushun  
  20.  * @date 2012-12-12 上午10:10:38  
  21.  *   
  22.  */  
  23. @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  24. @Service("sampleService")  
  25. @Scope("prototype")  
  26. public class SampleService implements ISample{  
  27.       
  28.     private HibernateTemplate h;  
  29.       
  30.     public void test() {  
  31.         List list = this.h.getSessionFactory().getCurrentSession().createSQLQuery("select * from cs_user").list();  
  32.         System.out.println("----------------------------------------");  
  33.         System.out.println(list.size());  
  34.     }  
  35.   
  36.     public HibernateTemplate getH() {  
  37.         return h;  
  38.     }  
  39.   
  40.     @Autowired(required=false)  
  41.     public void setH(@Qualifier(value="hibernateTemplate")HibernateTemplate h) {  
  42.         this.h = h;  
  43.     }  
  44.       
  45.       
  46. }  
/**
 * 
 */
package test;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/** 
 * @ClassName: SampleService 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author zhoushun 
 * @date 2012-12-12 上午10:10:38 
 *  
 */
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
@Service("sampleService")
@Scope("prototype")
public class SampleService implements ISample{
	
	private HibernateTemplate h;
	
	public void test() {
		List list = this.h.getSessionFactory().getCurrentSession().createSQLQuery("select * from cs_user").list();
		System.out.println("----------------------------------------");
		System.out.println(list.size());
	}

	public HibernateTemplate getH() {
		return h;
	}

	@Autowired(required=false)
	public void setH(@Qualifier(value="hibernateTemplate")HibernateTemplate h) {
		this.h = h;
	}
	
	
}


SpringBeanUtil.java 工具类

  1. package test;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6. import java.util.Properties;  
  7.   
  8. import javax.sql.DataSource;  
  9.   
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12. import org.hibernate.SessionFactory;  
  13. import org.springframework.beans.BeansException;  
  14. import org.springframework.context.ApplicationContext;  
  15. import org.springframework.context.ApplicationContextAware;  
  16. import org.springframework.core.io.Resource;  
  17. import org.springframework.stereotype.Component;  
  18.   
  19.   
  20. /**  
  21. * @ClassName: SpringBeanUtil  
  22. * @Description: TODO(spring功能类,用于获取bean)  
  23. * @author zhoushun 
  24. * @date 2012-11-27 下午04:22:36  
  25. *   
  26. */   
  27. @Component("springBeanUtil")//使用注解  
  28. public class SpringBeanUtil implements ApplicationContextAware {  
  29.     protected final static Log logger = LogFactory.getLog(SpringBeanUtil.class);  
  30.       
  31.     private static ApplicationContext ctx = null;  
  32.       
  33.     private static Map<String, Properties> propMap = new HashMap<String, Properties>(0);  
  34.       
  35.     public void setApplicationContext(ApplicationContext ctx)  
  36.             throws BeansException {  
  37.         SpringBeanUtil.ctx = ctx;  
  38.     }  
  39.       
  40.     public static Object getBean(String prop) {  
  41.         Object obj = ctx.getBean(prop);  
  42.         if (logger.isDebugEnabled()) {  
  43.             logger.debug("property=[" + prop + "],object=[" + obj + "]");  
  44.         }  
  45.         return obj;  
  46.     }  
  47.   
  48.     public static Properties getProperties(String filepath) {  
  49.         if (propMap.containsKey(filepath)) return propMap.get(filepath);  
  50.           
  51.         Resource resource = ctx.getResource(filepath);  
  52.         Properties prop = new Properties();  
  53.         try {  
  54.             prop.load(resource.getInputStream());  
  55.             propMap.put(filepath, prop);  
  56.             return prop;  
  57.         } catch (IOException e) {  
  58.             logger.error("can not find the resource file:[" + filepath + "]", e);  
  59.             return null;  
  60.         }  
  61.     }  
  62.   
  63.     public static DataSource getDataSource(String source) {  
  64.         return (DataSource) getBean(source);  
  65.     }  
  66.       
  67.     public static SessionFactory getSessionFactory() {  
  68.         return (SessionFactory) getBean("sessionFactory");  
  69.     }  
  70. }  
package test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;


/** 
* @ClassName: SpringBeanUtil 
* @Description: TODO(spring功能类,用于获取bean) 
* @author zhoushun
* @date 2012-11-27 下午04:22:36 
*  
*/ 
@Component("springBeanUtil")//使用注解
public class SpringBeanUtil implements ApplicationContextAware {
	protected final static Log logger = LogFactory.getLog(SpringBeanUtil.class);
	
	private static ApplicationContext ctx = null;
	
	private static Map<String, Properties> propMap = new HashMap<String, Properties>(0);
	
	public void setApplicationContext(ApplicationContext ctx)
			throws BeansException {
		SpringBeanUtil.ctx = ctx;
	}
	
	public static Object getBean(String prop) {
		Object obj = ctx.getBean(prop);
		if (logger.isDebugEnabled()) {
			logger.debug("property=[" + prop + "],object=[" + obj + "]");
		}
		return obj;
	}

	public static Properties getProperties(String filepath) {
		if (propMap.containsKey(filepath)) return propMap.get(filepath);
		
		Resource resource = ctx.getResource(filepath);
		Properties prop = new Properties();
		try {
			prop.load(resource.getInputStream());
			propMap.put(filepath, prop);
			return prop;
		} catch (IOException e) {
			logger.error("can not find the resource file:[" + filepath + "]", e);
			return null;
		}
	}

	public static DataSource getDataSource(String source) {
		return (DataSource) getBean(source);
	}
	
	public static SessionFactory getSessionFactory() {
		return (SessionFactory) getBean("sessionFactory");
	}
}


Test.java Main类

  1. /** 
  2.  *  
  3.  */  
  4. package test;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. /**  
  10.  * @ClassName: Test  
  11.  * @Description: TODO(这里用一句话描述这个类的作用)  
  12.  * @author zhoushun  
  13.  * @date 2012-12-12 上午10:13:51  
  14.  *   
  15.  */  
  16. public class Test {  
  17.     public static void main(String[] args){  
  18.         ApplicationContext applicationContext = null;    
  19.         String[] fileUrl = new String[]{"classpath*:*Context*.xml"};    
  20.         applicationContext = new ClassPathXmlApplicationContext(fileUrl);  //初始化 applicationContext  
  21.         //applicationContext = new FileSystemXmlApplicationContext(fileUrl);   
  22.         ISample s = (ISample)SpringBeanUtil.getBean("sampleService");  
  23.         s.test();  
  24.     }  
  25. }  
/**
 * 
 */
package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/** 
 * @ClassName: Test 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author zhoushun 
 * @date 2012-12-12 上午10:13:51 
 *  
 */
public class Test {
	public static void main(String[] args){
		ApplicationContext applicationContext = null;  
		String[] fileUrl = new String[]{"classpath*:*Context*.xml"};  
		applicationContext = new ClassPathXmlApplicationContext(fileUrl);  //初始化 applicationContext
		//applicationContext = new FileSystemXmlApplicationContext(fileUrl); 
		ISample s = (ISample)SpringBeanUtil.getBean("sampleService");
		s.test();
	}
}


applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"   
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xsi:schemaLocation="  
  8.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  10.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  11.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  12.       
  13.     <!-- =================================================================== -->  
  14.     <!-- Context Define                                                      -->  
  15.     <!-- =================================================================== -->  
  16.     <bean id="propertyConfigurer"  
  17.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  18.         <property name="locations">  
  19.             <list>  
  20.                 <value>classpath:database.properties</value>  
  21.             </list>  
  22.         </property>  
  23.     </bean>  
  24.           
  25.     <context:component-scan base-package="test" />  
  26.       
  27.     <bean   
  28.         id="dataSource"   
  29.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  30.         <property name="driverClassName" value="${hibernate.connection.driver_class}"/>  
  31.         <property name="url" value="${hibernate.connection.url}"/>  
  32.         <property name="username" value="${hibernate.connection.username}"/>  
  33.         <property name="password" value="${hibernate.connection.password}"/>  
  34.     </bean>  
  35.   
  36.     <!-- =================================================================== -->  
  37.     <!-- SessionFactory(For Hibernate)/ManagerFactory(For JPA) Define        -->  
  38.     <!--  ONLY ONE OF THEM SHOULD BE USED                                    -->  
  39.     <!-- =================================================================== -->  
  40.     <!--  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" spring 2.5之后继承的工厂类 -->  
  41.       
  42.     <bean id="sessionFactory"  
  43.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  44.         <property name="dataSource" ref="dataSource" />  
  45.         <property name="configLocation"  
  46.             value="classpath:hibernate.cfg.xml" />  
  47.             <property name="packagesToScan"><!-- 自动扫描注解 -->  
  48.             <list>  
  49.                 <value>com.wonders.*</value>  
  50.             </list>  
  51.             </property>  
  52.         <property name="configurationClass"  value="org.hibernate.cfg.AnnotationConfiguration"></property>  
  53.         <property name="lobHandler" ref="${jdbc.handler}" />  
  54.     </bean>  
  55.   
  56.   
  57.     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  58.         <property name="sessionFactory" ref="sessionFactory"></property>  
  59.     </bean>  
  60.       
  61.     <bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">  
  62.         <property name = "dataSource" ref="dataSource"/>  
  63.     </bean>  
  64.       
  65.     <bean id="oracleLobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">  
  66.         <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor" />  
  67.     </bean>  
  68.   
  69.     <bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler">  
  70.     </bean>  
  71.   
  72.     <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor" lazy-init="true" />  
  73.       
  74.       
  75.     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  76.         <property name="sessionFactory" ref="sessionFactory"/>  
  77.     </bean>  
  78.       
  79.       
  80.       
  81.     <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>  
  82.     <aop:aspectj-autoproxy/>  
  83.   
  84. </beans>  
<?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" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<!-- =================================================================== -->
	<!-- Context Define                                                      -->
	<!-- =================================================================== -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:database.properties</value>
			</list>
		</property>
	</bean>
		
	<context:component-scan base-package="test" />
	
	<bean 
		id="dataSource" 
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${hibernate.connection.driver_class}"/>
		<property name="url" value="${hibernate.connection.url}"/>
		<property name="username" value="${hibernate.connection.username}"/>
		<property name="password" value="${hibernate.connection.password}"/>
	</bean>

	<!-- =================================================================== -->
	<!-- SessionFactory(For Hibernate)/ManagerFactory(For JPA) Define        -->
	<!--  ONLY ONE OF THEM SHOULD BE USED                                    -->
	<!-- =================================================================== -->
	<!--  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" spring 2.5之后继承的工厂类 -->
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation"
			value="classpath:hibernate.cfg.xml" />
			<property name="packagesToScan"><!-- 自动扫描注解 -->
		    <list>
		        <value>com.wonders.*</value>
		    </list>
			</property>
		<property name="configurationClass"  value="org.hibernate.cfg.AnnotationConfiguration"></property>
		<property name="lobHandler" ref="${jdbc.handler}" />
	</bean>


	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
	    <property name = "dataSource" ref="dataSource"/>
	</bean>
	
	<bean id="oracleLobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
		<property name="nativeJdbcExtractor" ref="nativeJdbcExtractor" />
	</bean>

	<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler">
	</bean>

	<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor" lazy-init="true" />
	
	
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       	<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	
	
	<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
	<aop:aspectj-autoproxy/>

</beans>


其余配置文件不一一给出,经测试 成功!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值