Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to narrow visibility of bean in Spring

Tags:

java

spring

Lets assume that we have 3 classes:

@Component
public class A {
}

@Component
public class B {
}

@Component
public class C {
    @Autowired
    public C(A a, B b) { }
}

By default, each bean sees any other defined bean:

  • A sees B and C
  • B sees A and C
  • C sees A and B.

What I want to achieve is to limit visibility of bean A:

  • A sees no other bean
  • B sees A and C
  • C sees B and C

I thought that I can create two contexts: common, which holds only A bean definition, and child context which sees all beans defined in the first context and also declares its own beans (B and C). Unfortunately, I didn't find any way to do this with Java Config.

Do you know any way to achieve such solution?

like image 466
milus Avatar asked Nov 09 '22 16:11

milus


1 Answers

I'm not sure if it's OK if C can see A (looks like maybe that's desired and there is just a typo). If it is OK, then I think the following will work:

Since you are using Spring annotations, then the beans can be package scoped.

http://sahits.ch/blog/blog/2014/02/16/package-private-beans/

That should do it:

package the.first
@Component
public class A {
}
package the.second
@Component
//package protected
class B {
}
package the.second
@Component
//package protected
class C {
}
like image 95
April Papajohn Avatar answered Nov 14 '22 23:11

April Papajohn