【问题标题】:FactoryBean @Resource vs @AutowiredFactoryBean @Resource 与 @Autowired
【发布时间】:2020-05-04 21:15:26
【问题描述】:

我在 Spring Boot 应用程序中的项目类:

package com.example.demo;

public class FirstModel {
    public String getString(){
        return "first model";
    }
}
package com.example.demo;

public class SecondModel {
    public String getString(){
        return "second model";
    }
}

package com.example.demo;

import org.springframework.beans.factory.FactoryBean;

public class MyFactory implements FactoryBean {

    Class<?> clazz;

    @Override
    public Object getObject() throws Exception {
        if (clazz.equals(FirstModel.class)) return new FirstModel();
        else return new SecondModel();
    }

    @Override
    public Class<?> getObjectType() {
        return clazz;
    }
}
package com.example.demo;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfiguration {

    @Bean
    public MyFactory getMyFactory(){
        MyFactory myFactory = new MyFactory();
        myFactory.clazz = SecondModel.class;
        return myFactory;
    }
}
package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class HelloController {

    @Resource
    SecondModel secondModel;

    @RequestMapping("/")
    public String index() {
        return firstModel.getString();
    }

}

为什么当我通过@Resource 注解注入时它工作正常,但是当我使用@Autowired 时

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class HelloController {

    @Autowired
    SecondModel secondModel;

    @RequestMapping("/")
    public String index() {
        return secondModel.getString();
    }

}

Intellij Idea 这么说

“无法自动装配。找不到 'SecondModel' 类型的 bean”,但是当我运行应用程序时,它也可以像 @Resource 一样正常工作

@Resource 和@Autowired bean 检测在编译时或运行时有区别吗?我知道@Resource 中是否没有属性,它的工作方式为@Autowired 按类型。

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

要使用@Autowired 注释,该类的bean 应该存在。 要初始化任何类的全局 bean,您必须将 @Service 或此类注释应用于该类。

就像你的情况 Class SecondModel 一样:

package com.example.demo;

@Service
public class SecondModel {
    public String getString(){
        return "second model";
    }
}

有更多的注解可以替代@Service,这取决于该类的功能。

喜欢@Component 或@Repository Refer here

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 2014-12-14
    • 2016-02-18
    • 2015-09-28
    相关资源
    最近更新 更多