@Component 泛指组件的注册bean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Calvin_1016280226/article/details/79600105


@Component 组件的注册bean


1.@Component 思维导图



2.@Component 思维导图
1.注册Bean

/**
* Created by Calvin on 2018/3/13
*/

/**
* @Component 注册 Bean
* @Component 泛指组件,当组件不好归类为哪一类的时候,使用该注解
* @Component 标注在类上
*/
public class Component {

public void init(){
System. out .println( "Component_Bean 初始化" );
}

public void runtime(){
System. out .println( "Component_Bean 加载执行中" );
}
}


2. 自动扫描 basePackages 下为 Bean 包路径: com.spring.annotation.component

import org.springframework.context.annotation. ComponentScan ;
import org.springframework.context.annotation. Configuration ;

/**
* Created by Calvin on 2018/3/14
*/

@Configuration
/**
* @ComponentScan 自动扫描 basePackages 下为 Bean 包路径
*/
@ComponentScan (basePackages = " com.spring.annotation.component " )
public class Component_Configuration {
Component_Configuration(){
System. out .println( "Spring 容器初始化" );
}
}


如同,在spring-configuration.xml 中配置
<? xml version ="1.0" encoding ="UTF-8" ?>
xmlns: util =" http://www.springframework.org/schema/util " xmlns: task =" http://www.springframework.org/schema/task " xsi :schemaLocation ="

< context :component-scan base-package =" com.spring.annotation.component " use-default-filters ="false" >
    < context :include-filter type ="annotation" expression =" org.springframework.stereotype.Component " />
</ context :component-scan >


3.获取实例化对象

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* Created by Calvin on 2018/3/14
*/
public class Component_Test {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Component_Configuration. class );
        // 获取Bean
        Component component = applicationContext.getBean(Component. class );
        component.init();
        component.runtime()
    }
}


运行结果:
三月 14, 2018 1:04:54 上午 o rg.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@735f7ae5: startup date [Wed Mar 14 01:04:54 CST 2018]; root of context hierarchy
Spring 容器初始化
Component_Bean 初始化
Component_Bean 加载执行中



3.@Component 流程





猜你喜欢

转载自blog.csdn.net/Calvin_1016280226/article/details/79600105