Spring注入失败

尽管书看了厚厚一本,但实际用起来,还是经常会碰到一些问题。
再次一一进行记录。


Spring本质是一个容器的管理工具,所以你如果将要依赖它的注入功能。你就不能去手动new一个对象。

例子:

B是一个bean
class A{
@Autowired
B b;
}
这时,c想用注入了B的A,则A也要在C中依靠Spring进行注入
把A也设置成一个bean
class C{
@Autowired
A a;
}
而不能去new一个A,如果是自己new的,Spring无法将B注入到A中

很多时候,我们的job都会通过new job的方式进行使用,但如果job中有依赖自动注入,如何解决呢?
参考文档:
单例注入到多例是一个自然的方式,但多例如何注册到单例呢?注入的过程是在单例的实例化过程中的, 且只有一次
Spring官方文档给出的是 Method Injection的方式,例子中的commod,你可以根据个人需求,设置为prototype形式

public class CommandManager implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public Object process(Map commandState) {
        // grab a new instance of the appropriate Command
        Command command = createCommand();
        // set the state on the (hopefully brand new) Command instance
        command.setState(commandState);
        return command.execute();
    }

    protected Command createCommand() {
        // notice the Spring API dependency!
        return this.applicationContext.getBean("command", Command.class);
    }

    public void setApplicationContext(
            ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

自动注入时的父类和子类

实际碰到的问题,代码需要用到spring-data 里的RedisTemplate和StringRedisTemplate,使用@autowired,发现注入的无法实现。
1.@autowired 默认注入是 通过类型注入的,如果要通过beanID注入,则需要结合@Qualifier一起使用。
2.stringRedisTemplate是redisTemplate的子类,所以注入会发生问题,通过@Qualifier使用Id注入可解决问题


用spring管理的实例对象必须包含一个无参的构造参数

这个是改造一些他人不用Spring管理的框架中遇到的,用spring管理的实例对象必须包含一个无参的构造参数,否则会报错


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容