0

i'm just starting to learn the Spring framework and I'm just curious about how spring auto-wires a bean to another bean's private variable that has no setter methods. For example, I have a DependentBean which is dependent to a DependedBean...

@Component
public class DependentBean {
    @Autowired
    private DependedBean dependedBean; //this class has no "setDependedBean" setter method..
}

and for the DependedBean...

@Component
public class DependedBean{
     ...
}

When the spring boot application starts, it can set the dependedBean of the DependentBean even if the DependentBean object has no setter method for setting its dependedBean attribute. How does spring do that? I'm just curious...

Paul
  • 275
  • 1
  • 2
  • 13

2 Answers2

2

In Java you can use reflections to access a Class' private fields. See this Stack Overflow question for more details as to how that can be done.

Community
  • 1
  • 1
Jose Martinez
  • 11,452
  • 7
  • 53
  • 68
1

Reflection. Many dependency injection frameworks use reflection to process classes at runtime and modify their behavior.

Class#getDeclaredFields() returns an array of, well, all declared fields in the class (wrapped by Field API), including private ones. Field API allows you inspect annotations (isAnnotationPresent, getAnnotation, getAnnotations) and set its current value (set(Object, Object)).

Czyzby
  • 2,999
  • 1
  • 22
  • 40