Amit Gujarathi
Amit Gujarathi

Reputation: 1100

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

Upvotes: 1

Views: 1728

Answers (1)

xenteros
xenteros

Reputation: 15842

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 @Beans 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 @Beans when creating the Context.

Upvotes: 3

Related Questions