我不是 Spring 专业版,所以请耐心等待....
我有三个班级:
class SpringBeanA { public aMethod(){ ..... } } 类SpringBeanB { @Autowired SpringBeanA a; public bMethod(){ a.method(); } } class NONSpringClass { ..... b.method(); ..... }b .method()在通过实例 SpringBeanB b = new SpringBeanB()并通过自动装配SpringBeanB到NONSpringClass时,都会产生空指针错误。 / p>
自动装配:
class NONSpringClass { @Autowired SpringBeanB b; ..... b.method(); ..... }如何成功拨打 b.method()?
解决方案Spring初始化所有对象并保留它在Spring Application Context中。您可以通过几种不同的方式访问Application上下文中的对象。
首先创建一个spring配置类,将ApplicationContext注入私有属性并作为静态方法公开。
@Configuration class StaticApplicationContext实现ApplicationContextAware { static ApplicationContext applicationContext = null; public void setApplicationContext(ApplicationContext context)抛出BeansException { applicationContext = context; } / ** *请注意,这是一个静态方法,它暴露ApplicationContext ** / public static ApplicationContext getContext(){ return的applicationContext; } }现在你可以试试这个非spring类,
((SpringBeanB)StaticApplicationContext.getContext.getBean(b))。bMethod();请记住,在Spring上下文初始化之前调用getContext方法可能会导致NullPointerException。也不建议在弹簧容器外部访问bean。理想的方法是将所有豆子移到弹簧容器中进行管理。
如果你想从java Servelet访问SpringApplicationContext,请参考 WebApplicationContextUtils
I'm not a Spring pro, so please bear with me....
I have three classes:
class SpringBeanA { public aMethod() { ..... } } class SpringBeanB { @Autowired SpringBeanA a; public bMethod() { a.method(); } } class NONSpringClass { ..... b.method(); ..... }b.method() gives a null pointer error, both when accesed via the instances SpringBeanB b = new SpringBeanB() and autowiring SpringBeanB to NONSpringClass.
The autowiring:
class NONSpringClass { @Autowired SpringBeanB b; ..... b.method(); ..... }How can I successfully call b.method()?
解决方案Spring initializes all the objects and keep it in Spring Application Context. You have couple different ways to get access to objects inside Application context
First create a spring configuration class to inject ApplicationContext in to a private attribute and expose as static method.
@Configuration class StaticApplicationContext implements ApplicationContextAware{ static ApplicationContext applicationContext = null; public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } /** * Note that this is a static method which expose ApplicationContext **/ public static ApplicationContext getContext(){ return applicationContext; } }Now you can try this in your non spring class,
((SpringBeanB)StaticApplicationContext.getContext.getBean("b")).bMethod();Please keep in mind, invoking getContext method before spring context initialization may cause NullPointerException. Also accessing beans outside of spring container is not a recommended approach. Ideal way will be to move all beans in to spring container to manage.
If you want to access SpringApplicationContext from a java Servelet please refer WebApplicationContextUtils
更多推荐
如何从不在Spring容器中的类访问Spring Bean的方法
发布评论