简体   繁体   中英

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
带有@Component 注解的简单产品类

Simple DAO class with the @service annotation
带有 @service 注释的简单 DAO 类

Basic controller with the @Autowired annotation to get DAO instance
带有@Autowired注解的基本控制器来获取DAO实例

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

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:
配置文件

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
获取DAO bean并调用获取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.

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.

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