注解方式配置bean

2019-03-08  本文已影响0人  阳光课代表
package com;

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

import com.config.ApplicationConfig;

@Component
public class MyMain {

    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);// 根据配置类获取Spring上下文环境
        String[] beanDefinitionNames = context.getBeanDefinitionNames();// 获取所有在容器中注册的类名称
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
    }

}

package com.config;

import org.springframework.context.annotation.ComponentScan;

/**
 * Spring默认是不开启组件扫描bean的,必须使用@ComponentScan注解显示开启。若不指定参数,默认扫描该注解所在包下的所有被@Controller、@Component...等修饰的类
 * 注意:com.*代表的是com子包中的类,com包中的类不算
 */
@ComponentScan(basePackages = {"com.bean", "com.*"})
public class ApplicationConfig {
    
}

package com.bean;

import org.springframework.stereotype.Component;

/**
 * 参数可以指定类名,默认使用首字母小写作为类名
 */
@Component("abc")
public class Student {
    public void say() {
        System.out.println("I am a student");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读