组件注册

组件注册

    • 1.@Configuration+@Bean给容器当中注册组件
      • 代码实现
    • 2.@ComponentScan自动扫描组件
      • 代码实现

1.@Configuration+@Bean给容器当中注册组件

代码实现

@ C o n f i g u r a t i o n : 告 诉 S p r i n g 这 是 一 个 配 置 类 \color{blue}{@Configuration:告诉Spring这是一个配置类} @ConfigurationSpring

@Configuration
public class MainConfig {
     
    /**
     * 给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
     */
    @Bean("person")
    public Person person() {
     
        return new Person("ly", 27);
    }
}
@Data
public class Person {
     
    @Value("ly")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    @Value("${person.nickName}")
    private String nickName;

    public Person(String name, Integer age) {
     
        super();
        this.name = name;
        this.age = age;
    }

    public Person() {
     
        super();
    }
}

测 试 \color{red}{测试}

public class MainTest {
     
    public static void main(String[] args) {
     
        //注解的方式创建一个bean
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);

        String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
        Arrays.stream(namesForType).forEach(System.out::println);
    }
}

2.@ComponentScan自动扫描组件

代码实现

@Controller
public class BookController {
     
}
@Service
public class BookService {
     
}
@Repository
public class BookDao {
     
}
@Configuration
@ComponentScan(value = "com.ly.springannotation")
public class MainConfig {
     
}
    /**
     * @param
     * @return void
     * @Description: 获取容器当中所有定义bean的名字
     * 测试@ComponentScan 包扫描
     * @author luoyong
     * @create 21:44 2019/12/28
     * @last modify by [LuoYong 21:44 2019/12/28 ]
     */
    @Test
    public void test1() {
     
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        //获取容器当中所有定义bean的名字
        Arrays.stream(beanDefinitionNames).forEach(System.out::println);
    }

你可能感兴趣的:(spring)