We have to share our code base with a partner for developing, but we don't want to reveal the implementation of some services.
Say we have an interface FooService
and its implementation FooServiceImpl
.
public interface FooService
{
void doSomething();
}
@Service
public class FooServiceImpl implements FooService
{
@Override
public String doSomething();
{
...
}
}
Many other classes autowire this service in and call doSomething(). For example:
@Service
public class BarServiceImpl implements BarService
{
@Autowired
private FooService fooService;
@Override
public String validate();
{
fooService.doSomething();
...
}
}
If I just delete FooServiceImpl
, of course a NoSuchBeanException
will be thrown while starting. If I use @Autowired(required = false)
everywhere that FooService is autowired, a NullPointerException
will be thrown at runtime whenever doSomething()
gets called.
Besides the removal of each method body in FooServiceImpl manually, is there any other way to work this around?
Any help is appreciated.
First of all, as @AdrianShum and @chrylis commented, you need an implementation of
FooService
forBarServiceImpl.validate()
to work. So it's not clear what you mean by "don't want to reveal the implementation of some services".FooService
inBarServiceImpl
, scanning will be done to find a bean ofFooService
type. As you don't have any implementation ofFooService
, this error occurs.required=false
, above problem is neglected during initialization. But theprivate FooService fooService
will have aNULL
value obviously. So exception occurs when you callfooService.doSomething()
.@Component
(or similar thing) on yourinterface
. From the Spring docs, "This annotation is for the implementation classes to be autodetected through classpath scanning". Then there will be NoSuchBeanException, as you have no implementation classes.So, you can't autowire an interface without any implementation in Spring.