Spring 和 @Autowired - 自动装配何时发生?
我有一个类,其工作方式如下:
@Component
public class MyClass
{
@Autowired
public void setDataSource(DataSource dataSource)
{
...
}
public void doSomethingUsingDataSource()
{
// use autowired datasource
}
}
我的 applicationContext.xml 包含以下内容:
<context:load-time-weaver/>
<context:component-scan base-package="mypackage" />
如果我在另一个类中实例化 MyClass,则效果很好:
MyClass mc = new MyClass();
mc.doSomethingUsingDataSource();
但是,如果 MyClass 是单例:
@Component
public class MyClass
{
private static MyClass mc;
@Autowired
public void setDataSource(DataSource dataSource)
{
...
}
private void doSomethingUsingDataSource()
{
// use autowired datasource
}
public static void doSomething()
{
if (mc == null)
{
mc = new MyClass();
}
mc.doSomethingUsingDataSource();
}
}
并且我调用
MyClass.doSomething();
,则我会得到一个 NPE,因为 dataSource 为 null。
如果以这种方式创建我的类的新实例,Spring 是否无法设置数据源?或者我需要稍微改变一下我的配置吗?由于第一个版本有效,看来我的配置是正确的。
谢谢,
保罗
I have a class that works like so:
@Component
public class MyClass
{
@Autowired
public void setDataSource(DataSource dataSource)
{
...
}
public void doSomethingUsingDataSource()
{
// use autowired datasource
}
}
My applicationContext.xml contains this:
<context:load-time-weaver/>
<context:component-scan base-package="mypackage" />
This works fine if I instantiate a MyClass in another class:
MyClass mc = new MyClass();
mc.doSomethingUsingDataSource();
However, if MyClass is instead a singleton:
@Component
public class MyClass
{
private static MyClass mc;
@Autowired
public void setDataSource(DataSource dataSource)
{
...
}
private void doSomethingUsingDataSource()
{
// use autowired datasource
}
public static void doSomething()
{
if (mc == null)
{
mc = new MyClass();
}
mc.doSomethingUsingDataSource();
}
}
and I call
MyClass.doSomething();
then I get a NPE because dataSource is null.
Is Spring unable to set the datasource if a new instance of my class is created in this way? Or do I need to change my configuration a bit? Since the first version works it appears my configuration is correct.
Thanks,
Paul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后我通过删除自动装配解决了这个问题。我让我的类实现 ApplicationContextAware 并在 setApplicationContext 方法中设置数据源,如下所示:
通过这样做,我能够使用静态方法使我的类保持单例。
保罗
In the end I worked it out by removing the autowiring. I made my class implement ApplicationContextAware and set the data source in the setApplicationContext method, like so:
By doing this I was able to keep my class a singleton with static methods.
Paul