You're confusing several Spring concepts here.
First, @Component
is used for program components, generally objects that provide some service that other pieces of the program need. It is not intended for data objects such as your Employee
class, and data objects that are runtime data (and not configuration objects) shouldn't be autowired, they should be passed in to the specific method calls that operate on them.
@ModelAttribute
tells Spring that it should add whatever is being annotated to the MVC Model
object so that it's available to the controller and view. This has nothing to do at all with @Autowired
.
Here's what's happening in your code:
- Your
Employee
class is annotated@Component
, so Spring creates a singleton bean and registers it in the context. This bean never has its fields set, so they'renull
, but the bean itself exists, so it's wired into your controller'sempl
field. This is why you don't get aNullPointerException
, which you would if the autowiring really weren't working. - Your
@ModelAttribute
is evaluated by Spring and added to theModel
for each request. However, you never pass this model to any of your controllers, so they never see it. - Your controller methods create new, empty
ModelAndView
objects with nothing in them. - They then read the completely different, empty
Employee
object that was injected intoempl
and print out thenull
value on the fields (but don't throwNullPointerException
s because the autowiring succeeded).