spring 单独获取 bean方法

来源:互联网 发布:淘宝子账号有风险吗 编辑:程序博客网 时间:2024/04/29 20:26
spring 单独获取 bean方法


package com.vv.im.group;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * 
 * @author 007
 * @date Jan 26, 2015 1:03:07 PM
 * @version V1.0
 * @Description: TODO(获取bean)
 * 
 */
public class SpringContextHelper implements ApplicationContextAware {
private static ApplicationContext context = null;
public static SpringContextHelper springHelper = new SpringContextHelper();


public final static SpringContextHelper getInstance() {
return springHelper;
}


private SpringContextHelper() {
super();
}


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}


public static Object getBean(String name) {
return context.getBean(name);
}


}


1、spring 单独获取 bean方法




 
2、关于Spring事务中的java.lang.ClassCastException $Proxy0 cannot be cast to
 
   在使用Spring事务管理时,肯定有很多人都会遇到这样的异常:java.lang.ClassCastException: $Proxy0 cannot be cast t.这个问题的解决办法有两种。
        Spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。
        所以,解决办法是,如果用JDK动态代理,就必须为被代理的目标实现一个接口(要注意的地方是:需要将ctx.getBean()方法的返回值用接口类型接收);如果使用CGLIB强制代理,就必选事先将CGLIB包导入项目,设置beanNameAutoProxyCreator的proxyTargetClass属性为true。




3、springmvc框架中使用事物,需要在




springmvc.xml
<context:component-scan base-package="com.will" >      
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />    
</context:component-scan>  




Spring容器优先加载由ServletContextListener(对应applicationContext.xml)产生的父容器,而SpringMVC(对应mvc_dispatcher_servlet.xml)产生的是子容器。子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service。




http://blog.csdn.net/z69183787/article/details/37819831
0 0
原创粉丝点击