猿问

无法通过构造函数自动装配

我正在尝试通过构造函数自动装配一个类。


@Component

public class Test<T extends Something>{


@Autowired

public Test(Class<T> entity)

doSomething(enity);

}

...

当我运行代码时,我不断收到错误消息


Parameter 0 of constructor in com.test.Test required a bean of type 'java.lang.Class' that could not be found.

Action:

Consider defining a bean of type 'java.lang.Class' in your configuration.

有人可以告诉我这里哪里出错了。谢谢。


拉丁的传说
浏览 371回答 1
1回答

慕容森

它说你找不到标记为 Bean 等的 Class 类所以你需要有一个要注入的类声明为 @Bean ,@Component 等。这是一个例子:@Configuration&nbsp; &nbsp; public class Config {&nbsp; &nbsp; &nbsp; &nbsp; @Bean&nbsp; &nbsp; &nbsp; &nbsp; public<T> Class<T> tClass(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (some class to be returned);// you need to generify or pass some type of class which you want&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; //Here is injecting with no problems&nbsp; &nbsp; &nbsp; &nbsp; @Component&nbsp; &nbsp; &nbsp; &nbsp; public class Test<T> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; private Class<T> tClass;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Autowired&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public Test(Class<T> tClass) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.tClass = tClass;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }一些它如何更好地定义这样的架构,在这种情况下会更好:&nbsp; public interface Foo<T> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Class<T> getClassFromType();&nbsp; &nbsp; }@Componentpublic class FooIntegerImpl implements Foo<Integer>{&nbsp; &nbsp; @Override&nbsp; &nbsp; public Class<Integer> getClassFromType() {&nbsp; &nbsp; &nbsp; &nbsp; return Integer.class;&nbsp; &nbsp; }}@Componentpublic class FooStringImpl implements Foo<String>{&nbsp; &nbsp; @Override&nbsp; &nbsp; public Class<String> getClassFromType() {&nbsp; &nbsp; &nbsp; &nbsp; return String.class;&nbsp; &nbsp; }}@Componentpublic class Test {&nbsp; &nbsp; private List<Foo> foo;&nbsp; &nbsp; @Autowired&nbsp; &nbsp; public Test(List<Foo> foo) {&nbsp; &nbsp; &nbsp; &nbsp; this.foo = foo;&nbsp; &nbsp; }}例如,出于这样的目的,您可以定义对所有情况都通用的通用 API,实际上您可以定义 AbstractCrudOperations 并在有人需要继承它时定义杂物,将定义需要存在的对象类型并将定义一些方法实际上,在您的情况下,我不知道您要实现的逻辑,但基本错误是找不到 Class 作为 bean我认为这对你有帮助
随时随地看视频慕课网APP

相关分类

Java
我要回答