Question Details

No question body available.

Tags

java spring

Answers (2)

Accepted Answer Available
Accepted Answer
June 11, 2026 Score: 3 Rep: 4,066 Quality: High Completeness: 60%

I think this is technically feasible, but as far as I know, there is no built-in Spring mechanism that allows restricting a bean so that it can only be autowired into specific classes.

One possible approach would be to implement a custom BeanPostProcessor that inspects bean dependencies during startup. If it detects that MyBean is being injected into a class outside the allowed set, it can throw an exception and fail the application startup, smth like this:

@Component
public class MyBeanUsageValidator implements BeanPostProcessor {

@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

for (Field field : bean.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Autowired.class) && field.getType() == MyBean.class) {

// check whether allowed or not, for example: if (!AllowedBean.class.isAssignableFrom(bean.getClass())) { throw new BeanCreationException( "MyBean can only be injected into AllowedBean"); } } }

return bean; } }

Whether this is the right solution depends on the constraints. For example, if MyBean can be instantiated without being registered as a Spring bean, that might be a simpler approach. Otherwise, some custom validation logic during context initialization would probably be required.

June 11, 2026 Score: 4 Rep: 53 Quality: Low Completeness: 50%

Short Answer is No, Spring does not have a native concept of "private" or "local" beans. Once registered via @Bean, a bean is part of the shared application context and can be autowired anywhere.

One thing you can try out is to hold myBean as a private field and not annotate with @Bean but If MyBean itself needs Spring-managed lifecycle features, then it must be a @Bean and there is no enforcement mechanism afaik to restrict its injection. In that case, the best you can do is a documentation/review convention, like renaming it to _internalMyBean or something of the effect.