简体   繁体   中英

Spring Autowired Class

When we annotate a class as @Autowired , does it HAVE to be a interface or can it be a class?

All the examples of using Spring I have seen, use an interface and then implement it on a class. The interface type is then used to call a function on the Concrete class. Can we not just simply add @Autowired to a concrete class rather than an interface.

I know of the Programme to a interface analogy in JAVA, but if u are not depending on Polymorphism, then why to write an interface?

No, you don't have to use interfaces, this is completely fine as far as Spring is concerned:

@Service
public class FooService {
    @Autowired
    private FooDao fooDao;
}

or you can even go for construction injection:

@Service
public class FooService {

    private final FooDao fooDao;

    public FooService(FooDao fooDao) {
        this.fooDao = fooDao;
    }
}

Often interfaces are anachronic practice repeated by every subsequent generation. Don't use them if they are not required. And they aren't required if they will always have just one implementation or if you want to mock such a class (modern mocking frameworks mock classes without any problem).

There is also nothing wrong in injecting concrete classes, like FooDao in example above. It has some technical implications wrt. proxying, but nothing that can't be comprehended.

Technically @Autowired could be used for an implementation or an interface. Spring doesn't care about it. Injecting an interface is a design strategy.

@Autowired can also be used with a class instead of interface. But, using interfaces would be a better practice , since it reduces hard coupling between the components.

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