Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public Access Modifier and Module Exporting for Spring Beans

Tags:

java

spring

Must Spring bean classes, the classes of the objects that the Spring application context sets up, be public classes, for Spring to create those objects? Obviously, if your beans access other beans of yours in different packages, your beans will have to be public to interact with each other. My question is whether all your bean classes must be public.

As the Spring code itself is in a different package from the package you code is in, conceptually Spring is doing something that ought to require public access to your classes. On the other hand, Spring is using reflection to create the beans, so it probably does not need your classes to be public.

It addition to the package access types, from Java 9 we have Java Modules. Do the classes need to be public and exported from your module, if you put them in a module?

like image 777
Raedwald Avatar asked Sep 18 '13 09:09

Raedwald


1 Answers

No, not all classes have to be public. Spring can instantiate package-private classes using reflection like you mentioned without any problems..

If a package-private bean is managed by the IoC container and used by classes in the same package it's no problem. Problems only arise when you try to wire that bean across packages. Which is quite obvious of course.

like image 136
Bart Avatar answered Oct 09 '22 00:10

Bart