stackuser
stackuser

Reputation: 23

Spring boot web java configuration not working

I'm just starting off with Spring , I have created a basic Spring boot web app with - Thymeleaf templates, JPA and Mysql.

When I use the autowiring and annotate all the classes everything works. Here is an example of the working code.

Simple product class with the @Component annotation
Simple product class with the @Component annotation

Simple DAO class with the @service annotation
Simple DAO class with the @service annotation

Basic controller with the @Autowired annotation to get DAO instance
Basic controller with the @Autowired annotation to get DAO instance

So when I call the get method , I'm able to see a list of products: 2 products displayed
2 products displayed

Now when I transition to the java configuration , this stops working. I commented out the annotations and added a new java config file.

the @Autowiring annotation also removed from the Controller

Added a java class with the @Configuration, see config file:
config file

Just to make sure the context loaded the beans, I took the configurable context that was returned by the run method and checked if the bean was loaded.

Get the DAO bean and call the method to get the Product line items
Get the DAO bean and call the method to get the Product line items

This also works as I could see the object was not null. Also I could get a count of the products in the output immediately after the application was started.

Everything is ok till here and the application has started. But now when I access the URL - I get an error

Summary This example is only being done to understand Spring and is not following proper DDD practices.

Here is a summary of the steps, the issues are in step 4(b)

  1. DAO creates 2 Product instances, puts into a list and returns it.
  2. The DAO is injected into the controller. The controller calls the getproducts() on the DAO and returns the list of products.
  3. Everything works with the component and service Annotations combined with @Autowiring
  4. Problem comes when I use a Java configuration. (a) After application startup I get the context and verify if the beans are loaded. (I'm doing this in the main application.) (b) Only when I hit the url and when the controller tries to call the method on the DAO I get the problem.

Upvotes: 0

Views: 663

Answers (1)

R.G
R.G

Reputation: 7131

Declare a constructor for HomeController as follows

@Controller
public class HomeController{

   private final ProductDao dao;

    public HomeController(ProductDao dao){
       this.dao = dao;
    }
 
  //... rest of the code
}

Reference : Spring Boot Reference Documentation - Spring Beans and Dependency Injection

If a bean has one constructor, you can omit the @Autowired

Note : Share actual code instead of images for reference.

Upvotes: 1

Related Questions