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

service 类 及 接口 

ISample.Java

[java] view plain copy
print ?
  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

[java] view plain copy
print ?
  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 工具类

[java] view plain copy
print ?
  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 propMap = new HashMap(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 propMap = new HashMap(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类

[java] view plain copy
print ?
  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

[java] view plain copy
print ?
  1. "1.0" encoding="UTF-8"?>  
  2. "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.       
  15.       
  16.     "propertyConfigurer"  
  17.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  18.         "locations">  
  19.               
  20.                 classpath:database.properties  
  21.               
  22.           
  23.       
  24.           
  25.     package="test" />  
  26.       
  27.     
  28.         id="dataSource"   
  29.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  30.         "driverClassName" value="${hibernate.connection.driver_class}"/>  
  31.         "url" value="${hibernate.connection.url}"/>  
  32.         "username" value="${hibernate.connection.username}"/>  
  33.         "password" value="${hibernate.connection.password}"/>  
  34.       
  35.   
  36.       
  37.       
  38.       
  39.       
  40.       
  41.       
  42.     "sessionFactory"  
  43.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  44.         "dataSource" ref="dataSource" />  
  45.         "configLocation"  
  46.             value="classpath:hibernate.cfg.xml" />  
  47.             "packagesToScan">  
  48.               
  49.                 com.wonders.*  
  50.               
  51.               
  52.         "configurationClass"  value="org.hibernate.cfg.AnnotationConfiguration">  
  53.         "lobHandler" ref="${jdbc.handler}" />  
  54.       
  55.   
  56.   
  57.     "hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  58.         "sessionFactory" ref="sessionFactory">  
  59.       
  60.       
  61.     "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">  
  62.         "dataSource" ref="dataSource"/>  
  63.       
  64.       
  65.     "oracleLobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">  
  66.         "nativeJdbcExtractor" ref="nativeJdbcExtractor" />  
  67.       
  68.   
  69.     "defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler">  
  70.       
  71.   
  72.     "nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor" lazy-init="true" />  
  73.       
  74.       
  75.     "txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  76.         "sessionFactory" ref="sessionFactory"/>  
  77.       
  78.       
  79.       
  80.       
  81.     "txManager" proxy-target-class="true"/>  
  82.       
  83.   
  84.   


	
	
	
	
	
		
			
				classpath:database.properties
			
		
	
		
	
	
	
		
		
		
		
	

	
	
	
	
	
	
	
		
		
			
		    
		        com.wonders.*
		    
			
		
		
	


	
		
	
	
	
	    
	
	
	
		
	

	
	

	
	
	
	
       	
	
	
	
	
	
	



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



你可能感兴趣的:(Java,Spring,spring,本地应用,class)