0

I saw that injecting ShopRepo with @Autowire annotation is working but when I try to do it with xml sometimes it works and sometimes it doesn't (also, intellij says that I cannot use an abstract bean as a property). Why it is working with the annotation and with the xml config doesn't always work (which is the difference)? And how could I make it work with xml config?

The code looks like this:

public interface ShopRepo extends JpaRepository<Product, Long> {
    @Override
    Optional<Product> findById(Long aLong);
}

public class ShopController {

    //@Autowired
    private ShopRepo shopRepo;


    public void setShopRepo(ShopRepo shopRepo) {
        this.shopRepo = shopRepo;
    }

    public Product findProduct(Long id) {
        return shopRepo.findById(1l).orElse(new Product());
    }
}


    <jpa:repositories base-package="com.example.shop.repository"/>

<bean id="shopRepo" class="com.example.shop.repository.ShopRepo" abstract="true"/>

<bean id="shopController" class="com.example.shop.controller.ShopController">
    <property name="shopRepo" ref="shopRepo"/>
</bean>
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Lexy
  • 25
  • 3
  • Consider separating the xml defintion from java code by writing something in between such as 'JPA mapping in XML'. – soufrk Jun 08 '18 at 10:17

1 Answers1

1

When you use @Autowire, you are actually doing autowire by type. @Autowire simply injects the implementation of shopRepo bean. The implementation of shopRepo is instantiated dynamically by jpa repositories, usually during the startup of spring container .

Your xml configuration is not doing any autowiring by type , it is attempting to inject the bean with id "shopRepo" into the shopcontroller bean. The shopRepo definition in your xml is simply a definition and not the name the actual implementation created by jpa repository.

You can follow this in your xml file. Hope this helps.

<bean id="shopRepo" class="com.example.shop.repository.ShopRepo" abstract="true"/>
<bean id="shopController" class="com.example.shop.controller.ShopController" autowire="byType">   
</bean>
Amit Parashar
  • 1,447
  • 12
  • 15