zoukankan      html  css  js  c++  java
  • spring新注解

    一、@configuration注解的配置类

    /*
    @Configuration:指定当前类是一个配置类
    @ComponentScan:用于通过注解指定spring在创建容器时要扫描的包
        属性:value、basePackages是一个数组
        作用:相当于在spring的xml配置文件中配置:
            <context:component-scan base-package="com.wuxi"></context:component-scan>
    @Bean:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
        属性:name:用于指定bean的id,当不写时,默认值是当前方法的名称
        当前方法参数:参数注入的规则与@Autowired一致,先匹配参数类型(Student和class),再匹配参数名称(student和id)
        当前方法参数加@Qualifier注解:注入的bean的id与属性value值匹配
    指定配置类方式:
        1、AnnotationConfigApplicationContext(Class<?>... componentClasses)
            构造函数参数中指定的类都为配置类,类上可以不加@Configuration注解,且这些类作为配置文件,为兄弟关系
        2、@ComponentScan注解的类首先得是配置类,@ComponentScan扫描到的,具有@Configuration注解的类,为配置类
        3、@Import属性value中指定的类为配置类,类上可以不加@Configuration注解,且这些类作为配置文件,为父子关系
    @PropertySource:用于指定properties文件的位置
        classpath:关键字:表示类路径下
    */
    @Configuration
    @ComponentScan("com.wuxi")
    @PropertySource("classpath:value.properties")
    public class SpringConfig {
    
        @Value("${student.name}")
        private String name;
    
        @Bean(name = "gradeConfig")
        public Grade createGrade(@Qualifier("createStudent") Student student) {
            return new Grade(student);
        }
    
        @Bean
        @Scope("singleton")
        public Student createStudent() {
            System.out.println(name);
            return new Student();
        }
    }

    二、properties配置文件

    student.name=mengmeiqi

    三、测试

    public class MySpringTest {
        public static void main(String[] args) {
            ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
            Grade grade = ac.getBean("gradeConfig", Grade.class);
            grade.studentMethod();
        }
    }
  • 相关阅读:
    lambda表达式
    各种模块化简介及演变过程
    filter-api文档
    RegExp正则表达式规则以及常用正则表达式
    各种循环遍历对比
    条件语句对比
    莫队小结
    停更公告
    POJ2728 Desert King
    笛卡尔树Cartesian Tree
  • 原文地址:https://www.cnblogs.com/linding/p/13665300.html
Copyright © 2011-2022 走看看