Stereotype Annotations

Stereotype annotations are used to create user objects.

@Component annotation – to mark a POJO to be managed by Spring as a Bean. This is equivalent to using <bean> tag in XML configuration.

What are all packages to be scanned for identifying the Component classes :

@ComponentScan("....")  (or) 
<context:component-scan base-package="......" />

Spring container will scan through the given package and sub packages for all classes marked with @Component annotation.

By default, Spring container uses class name marked with @Component annotation as the bean name in camelCase notation. 

The class name in camelCase notation is used to reference instantiated object name, nothing but the class name in camelCase notation is the bean name. [Default behavior]

Ex :

@Component
class Instructor {
   .....
}

// The class name in camelCase notation is used to reference 
// instantiated object name, nothing but bean name.
Instructor instructor = new Instructor();

// this is same as :
<bean name="instructor" class="org.rdayala.spring.basics.Instructor">
    .....
</bean>

However, to give a different bean name, instead of the class name in camelCase notation, we need to specify a name in @Component annotation.

@Component("inst")
class Instructor {
  .....
}

In this case, Spring container will create bean with the name "inst". It is same as :
<bean name="inst" class="org.rdayala.spring.basics.Instructor">
    .....
</bean>

 

@Scope annotation :

https://springframework4u.wordpress.com/spring-core/bean-scope/

@Value annotation :

valueannotation1

  • @Value with Primitives –> @Value(“<value>”)
@Value("10")
private int id = 5;

@Value("Raghu")
private String name;

Note : Annotations will override any value we assign to the fields.

  • @Value with Collection types

First, create standalone collection in XML configuration using util schema.

<util:list list-class="java.util.LinkedList" id="topicsList">
    <value>Java Web Services</value>
    <value>Core Java</value>
    <value>Spring Framework</value>
</util:list>

Second, we assign the list to the field using @Value annotation.

@Value("#{topicsList}")
private List<String> topics;
  • Injecting object types / reference types using @Autowired
@Autowired
private Profile profile;