简体   繁体   中英

Unable to define bean in spring boot

I have defined a class annotated it with @Configuration and defined method init and Defined it with annotation @Bean but when im trying to access that bean using auto-wired it gives me an error 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]

@Configuration
@EnableAutoConfiguration
public class Appconfig {

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

        int c=a+b;
        return c;
    }

And my controller class

 @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));


    }

Error

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]
└─────┘

Your dependencies are circular, which means, that to create A you need B which needs A .

@Configuration
@EnableAutoConfiguration
public class Appconfig {

    public int Sum(int a,int b){

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

will work but isn't a good practice. Configuration classes shouldn't be @Autowired .

In Spring Boot you can create @Bean s in two ways. One is defining a class as a @Bean :

@Bean
public class MyBean {

}

The other way is via the method:

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

Both of the above, will create @Bean s when creating the Context .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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