gpt4 book ai didi

java - FactoryBean @Resource 与 @Autowired

转载 作者:行者123 更新时间:2023-12-01 16:55:11 25 4
gpt4 key购买 nike

我在 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 注释注入(inject)时它工作正常,但是当我使用 @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 说

“无法 Autowiring 。找不到'SecondModel'类型的bean”,但是当我运行应用程序时,它也可以作为@Resource

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

最佳答案

使用 @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为了那个原因。

关于java - FactoryBean @Resource 与 @Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61601755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com