我正在开发某种应该由外部 java 应用程序调用的插件。
我的插件正在使用 Spring,因此我试图尽可能简化我的插件:
让我们考虑一下这是一个 3d 派对应用程序,它在其主要功能中调用我的插件。
public class ThirdPartyClass {
public static void main(String[] args) {
GeneralPlugin plugin = new MyPlugin();
plugin.init();
//calling ext. plugin functionality.
plugin.method1();
}
}
现在这是我的插件
package com.vanilla.spring;
@Component
public class MyPlugin implements GeneralPlugin{
@Autowired
Dao mydao;
public void init(){
//some initiation logic goes here...
}
public void method1(){
dao.delete();
}
}
现在我的道
package com.vanilla.spring;
Component(value="dao")
public class MyDao {
public void delete(){
//SOME DATABASE LOGIC GOES HERE!!!
}
}
现在我的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
<context:annotation-config />
<context:component-scan base-package="com.vanilla.spring"></context:component-scan>
</beans>
我的问题是我的 dao 是空的,我得到了
NullPointerException
访问 dao 对象时。一世
我相信这是因为我在应用程序上下文之外启动 bean,结果我的 Autowiring 无法正常工作。
有没有其他方法可以使 Autowiring 工作?
最佳答案
“Spring bean”就是这样:Java bean。除了通过继承或对象实例化赋予它们的能力之外,它们没有任何内在能力。
Spring Application Context 负责创建 bean 并“连接”它,这是在上下文中创建其他 bean 并使用结果调用 bean 的 setter(和构造函数)以配置它们的过程。为此,使用 XML 配置文件和注释来决定要创建什么以及将它放在哪里。
如果您不打算使用实际的应用程序上下文,那么您必须自己手动完成所有这些工作。也就是说,使用正确的数据源创建 DAO,创建插件 bean,并在插件 bean 上设置 DAO。
在这个特定示例中,由于第 3 方应用程序控制插件 bean 的实例化,因此您可能必须 a) 在插件构造函数中创建 DAO(这是您首先使用 Spring 避免的),或者 b) 在插件构造函数中创建一个应用程序上下文,并通过查询上下文来引用插件需要的 bean。这不像让上下文做所有事情那么有用,但至少您不必手动配置应用程序使用的其余 bean(使用用户名、连接 URL 等)。
如果你走第二条路线,那么你将需要在类路径中某处的 Spring 配置文件,或者以其他方式能够被插件 bean 引用。
关于java - 如何在 Spring 应用程序上下文之外创建 Spring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058368/