繁体   English   中英

无法在spring boot中定义bean

[英]Unable to define bean in spring boot

我已经定义了一个用@Configuration和定义的方法init注释它的类,并使用注释@Bean定义它但是当我尝试使用自动连接访问该bean时它给了我一个错误应用程序上下文中的一些bean的依赖关系一个周期:

┌─────┐
|  Sum defined in class path resource [com/example/Application/Appconfig.class]

@Configuration
@EnableAutoConfiguration
public class Appconfig {

    @Bean
    public int Sum(int a,int b){

        int c=a+b;
        return c;
    }

和我的控制器类

 @Autowired
    Appconfig appconfig;


    @PostMapping(value = "/api/{id1}/{id2}")
    public void math(@PathVariable int id1,@PathVariable int id2){

        appconfig.Sum(id1,id2);
        System.out.println(id1);
        System.out.println(id2);
        System.out.println(appconfig.Sum(id1,id2));


    }

错误

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  Sum defined in class path resource [com/example/Application/Appconfig.class]
└─────┘

您的依赖关系是循环的,这意味着,要创建A您需要B需要A

@Configuration
@EnableAutoConfiguration
public class Appconfig {

    public int Sum(int a,int b){

        int c=a+b;
        return c;
    }
}

会工作,但不是一个好的做法。 配置类不应该是@Autowired

在Spring Boot中,您可以通过两种方式创建@Bean 一个是将类定义为@Bean

@Bean
public class MyBean {

}

另一种方法是通过该方法:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

以上两者都将在创建Context时创建@Bean

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM