Spring注解开发之@Bean和@ComponentScan

时间:2020-08-28 12:05:46   收藏:0   阅读:70

组件注册

用@Bean来注册

  1. 搭建好maven web工程

  2. pom加入spring-context,spring-core等核心依赖

  3. 创建实例类com.hjj.bean.Person, 生成getter,setter方法

    public class Person {
        private String name;
        private int age;
    }
    
  4. 创建com.hjj.config.MainConfig

    @Configuration   //告诉spring是一个配置类
    public class MainConfig {
    
        // 给容器中注册一个Bean,类行为返回值的类型,id默认是用方法名作为id
        @Bean("mikePerson")
        public Person person(){
            return new Person("mike",20);
        }
    }
    
  5. 主测试类

    public class MainTest {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
            Person bean = applicationContext.getBean(Person.class);
            System.out.println(bean);
    
            String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
            for (String type : beanNamesForType) {
                System.out.println(type);  //配置类中的方法名,注意:通过修改配置类的@bean value也可以修改
            }
        }
    }
    

@ComponentScan包扫描

  1. 配置类中MainConfig.java

    @Configuration   //告诉spring是一个配置类
    @ComponentScan("com.hjj") // 扫描包的路径
    public class MainConfig {
    
        // 给容器中注册一个Bean,类行为返回值的类型,id默认是用方法名作为id
        @Bean("mikePerson")
        public Person person(){
            return new Person("mike",20);
        }
    }
    
    
  2. 新建测试的com.hjj.controller,service,dao

    @Controller
    public class BookController {
    }
    
    @Repository
    public class BookDao {
    }
    
    @Service
    public class BookService {
    }
    
  3. 单元测试

        @Test
        public void test01(){
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
            String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); //获取所有组件
            for (String beanDefinitionName : beanDefinitionNames) {
                System.out.println(beanDefinitionName);  
            }
        }
    
    
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!