Friday, December 11, 2020

Inversion of Control using Java Annotations instead of XML

 So far we've been using bean tags to describe our bean classes and to also set tags. Instead, we can more easily use a single tag in our configuration file that will enable us to use annotations similar to @Override. Here we save so much space while also writing simpler to understand code.


In our configuration file, we eliminate all current bean tags and simply replace with

<context:component-scan base-package="com.rogersentongo.springdemo"/>


This provides spring with the base package to search for components


Then for every class implentation we add the annotation @Component in order to access that bean

@Component

public class TennisCoach implements Coach{


We can now access the tennis coach implementation using the string "tennisCoach". Same as class name except the first letter is lower case. Another option is to specify the name if you want


@Component("thatgoodCoach")

public class TennisCoach implements Coach{


Now we can access the bean using the string "thatgoodCoach"!!

No comments:

Post a Comment