如果一个个的Bean使用注解@Bean注入到Spring IoC容器中,那将是一件很麻烦的事情.好在Spring还允许我们进行扫描装配Bean到IoC容器,对于扫描装配而言使用的注解是@Component和@ComponentScan.@Component是标明那个类被扫描进入Spring IoC容器,而@ComponentScan则是标明采用何种策略去扫描装配Bean.
package com.springboot.chapter3.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component("user")
//@Component注解标明这个类将被Spring IoC容器扫描装配,
public class User {
@Value("1")
private Long id;
@Value("user_name_1")
private String userName;
@Value("note_1")
private String note;
}
package com.springboot.chapter3.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
//添加@ComponentScan,意味着它会进行扫描,但是它只会扫描AppConfig所在的当前包和其子包。
public class AppConfig {
}
测试扫描
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
User user = (User) applicationContext.getBean(User.class);
logger.info(user.getId().toString());