1、添加util方法:
package com.hzc.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 普通类调用Spring注解方式的Service层bean
* Created by HZC on 2015/10/21.
*/
public class SpringBeanFactoryUtils implements ApplicationContextAware {
private static ApplicationContext appCtx;
/**
* 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。
*
* @param applicationContext ApplicationContext 对象.
* @throws BeansException
* @author hzc
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appCtx = applicationContext;
}
/**
* 获取ApplicationContext
*
* @return
* @author hzc
*/
public static ApplicationContext getApplicationContext() {
return appCtx;
}
/**
* 这是一个便利的方法,帮助我们快速得到一个BEAN
*
* @param beanName bean的名字
* @return 返回一个bean对象
* @author hzc
*/
public static Object getBean(String beanName) {
return appCtx.getBean(beanName);
}
}
2、在spring的配置文件.xml中添加
<bean id="springBeanFactoryUtils" class="com.haier.util.SpringBeanFactoryUtils"/>
3、service方法
package com.hzc.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* Created by HZC on 2015/10/20.
*/
@Service("ckPayoffService")
public class CKPayoffServiceImpl implements ICKPayoffOrderService {
private static final Logger log = LoggerFactory.getLogger(CKPayoffServiceImpl.class);
/**
* 测试
*
* @author HZC
* @createDate 2015-10-21
*/
@Override
@Transactional
public void calculatePayoff() {
System.out.println("--------------------------gogogogogo---------------");
}
}
4、使用
CKPayoffServiceImpl ckps = (CKPayoffServiceImpl) SpringBeanFactoryUtils.getBean("ckPayoffService");
ckps.calculatePayoff();
在普通类中就可以调用service实例方法了,执行calculatePayoff方法,打印“————————–gogogogogo—————”