美文网首页
注解方式配置bean

注解方式配置bean

作者: 阳光课代表 | 来源:发表于2019-03-08 17:04 被阅读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");
    }
}

相关文章

网友评论

      本文标题:注解方式配置bean

      本文链接:https://www.haomeiwen.com/subject/bdxdpqtx.html