为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉丁的传说 2022-01-19 15:36:50
我正在尝试通过构造函数自动装配一个类。@Componentpublic class Test<T extends Something>{@Autowiredpublic 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.有人可以告诉我这里哪里出错了。谢谢。
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

它说你找不到标记为 Bean 等的 Class 类所以你需要有一个要注入的类声明为 @Bean ,@Component 等。


这是一个例子:


@Configuration

    public class Config {


        @Bean

        public<T> Class<T> tClass(){

            return (some class to be returned);// you need to generify or pass some type of class which you want 

        }


    }



    //Here is injecting with no problems

        @Component

        public class Test<T> {


            private Class<T> tClass;


            @Autowired

            public Test(Class<T> tClass) {

                this.tClass = tClass;

            }

        }

一些它如何更好地定义这样的架构,在这种情况下会更好:


  public interface Foo<T> {


         Class<T> getClassFromType();

    }


@Component

public class FooIntegerImpl implements Foo<Integer>{



    @Override

    public Class<Integer> getClassFromType() {

        return Integer.class;

    }

}


@Component

public class FooStringImpl implements Foo<String>{


    @Override

    public Class<String> getClassFromType() {

        return String.class;

    }

}


@Component

public class Test {


    private List<Foo> foo;


    @Autowired

    public Test(List<Foo> foo) {

        this.foo = foo;

    }


}

例如,出于这样的目的,您可以定义对所有情况都通用的通用 API,实际上您可以定义 AbstractCrudOperations 并在有人需要继承它时定义杂物,将定义需要存在的对象类型并将定义一些方法


实际上,在您的情况下,我不知道您要实现的逻辑,但基本错误是找不到 Class 作为 bean


我认为这对你有帮助


查看完整回答
反对 回复 2022-01-19
  • 1 回答
  • 0 关注
  • 370 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号