我有一个类(Class ABC),通过调用构造函数来实例化。Class ABC又有一个帮助类(Class XYZ),使用自动装配进行注入。
我们的应用程序是基于Spring MVC构建的,在服务器启动时没有看到任何异常。
但是我仍然发现Class XYZ为null。这是否是因为Class ABC没有由Spring容器实例化?
在这种情况下,我该如何使用自动装配?
谢谢。
我有一个类(Class ABC),通过调用构造函数来实例化。Class ABC又有一个帮助类(Class XYZ),使用自动装配进行注入。
我们的应用程序是基于Spring MVC构建的,在服务器启动时没有看到任何异常。
但是我仍然发现Class XYZ为null。这是否是因为Class ABC没有由Spring容器实例化?
在这种情况下,我该如何使用自动装配?
谢谢。
您可以使用此方法在非Spring Bean类中使用Spring Bean。
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext) {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}
现在你可以通过调用getApplicationContext()方法来获取applicationcontext对象。
通过applicationcontext,你可以像这样获取Spring Bean对象:
ApplicationContext appCtx = ApplicationContextUtils.getApplicationContext();
String strFromContext = appCtx.getBean(beanName, String.class);
ApplicationContextUtils
上添加 @Component
注解,否则在调用 ApplicationContextUtils .getApplicationContext()
方法时会返回 null。 - bluearrowApplicationContextAware
仅适用于Spring Bean本身的类(因此带有@Component
注释)。但是OP明确要求不是Spring Bean即不受Spring管理的类! - Peter Wippermann然后使用以下内容手动设置Bean值:ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
XYZ someXyz = (XYZ) context.getBean("MyXYZ");
正确的做法是:你不能只是在一个类上调用new
方法然后期望所有的依赖注入都能够自动完成;Spring必须管理这个bean才能发挥其全部魔力。
如果您能提供更多有关您使用情况的详细信息,我们可能会建议一些有用的选项。
对于像我这样只会基本Spring Boot并不熟悉行话的新手:
Ashish的答案对我有用,但是这篇文章提供了更详细的解释。
如果您不知道所需的bean的名称,请尝试查看此数组:
String[] names = context.getBeanDefinitionNames();
@Configurable(autowire = Autowire.BY_TYPE)
public class ABC {
@Autowire private XYZ xyz;
...
}
@Configuration
@EnableSpringConfigured
public class Application {
...
}
public class MyClass {
public void doSomething() {
ABC abc = new ABC(); // XYZ is successfully autowired
...
}
}
<context:component-scan base-package="com.mypackage.awesomeproject" />
第一个问题 - 是的,因为该类没有使用Spring进行初始化。 第二个问题 - 我认为你可以使用AspectJ支持 http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-using-aspectj
Application
)中获取上下文并将其保存在那里。public class Application {
public static ApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(Application.class, args);
}
}
Application.context.getBean("MyXYZ")
或类似的方式从任何地方获取一个bean。您可以使用@Configurable
注释来注释ABC
类。然后,Spring IOC将向ABC
类注入XYZ
实例。通常与AspectJ的AnnotationBeanConfigurerAspect
一起使用。
Spring有一个util类
BeanUtils.instantiateClass(clazz)
BeanUtils.instantiate(clazz)
YouClass ins = BeanUtils.instantiate(YouClass.class)