Tuesday, November 10, 2009

Spring autowiring of private fields with no set method

To autowire a private field with no setter method I always assumed Spring would manipulate the byte code using AspjectJ or something similar and create an "artificial" setter method, but it actually just uses reflection to change the access to the field using "setAccessible".  Take a look at the makeAccessible method in the internal spring class org.springframework.util.ReflectionUtils.  This likely won't work with a security manager in place so I wonder what happens in that case.

Interestingly also, I found that even if there is a setter for a public field annotated with @Autowired, Spring doesn't call the setter to set the value.  It set the value directly on the field.  It only appears to call the setter if the setter method is annotated...

1 comments:

  1. In this case, when I used an interface it's possible use private field with no set method?

    @Autowired
    private MyInterface object;

    ReplyDelete