@Component : Bean

POJO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.chap10.annotation.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "role")
public class Role {
@Value("1")
private Long id;
@Value("role_name_1")
private String roleName;
@Value("role_note_1")
private String note;

// setters and getters

Spring IoC does not know where to scan objects(POJO) with just this class. A Java Config is needed to tell Spring IoC where to scan this object;

i.e. for a Bean to be useful in Spring IoC container, two steps are entailed:

  1. POJO: Spring IoC: POJOs are created to be scanned to be bean;
  2. ComponentScan: 2nd step in Dependency Injection: where to find this bean, to inject resources into this empty bean
1
2
3
4
5
6
7
package com.chap10.annotation.pojo;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class PojoConfig {
}

main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.chap10.main;

import com.chap10.annotation.pojo.PojoConfig;
import com.chap10.annotation.pojo.Role;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AnnotationMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(PojoConfig.class);
Role role = context.getBean(Role.class);
System.err.println(role.getId());
}
}