【发布时间】: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 按类型。
【问题讨论】:
-
是的,有区别,
@Resources检测顺序执行,name,type,qualifier,而@Autowire顺序执行,type,qualifier,@987654335 @。 baeldung.com/spring-annotations-resource-inject-autowire 我无法回答 intellij 是如何处理这个问题的。
标签: java spring spring-boot