Spring注解驱动开发 详解Spring注解驱动开发之属性赋值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring注解驱动开发 详解Spring注解驱动开发之属性赋值

煎丶包   2021-05-26 我要评论
想了解详解Spring注解驱动开发之属性赋值的相关内容吗,煎丶包在本文为您仔细讲解Spring注解驱动开发的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring注解驱动开发,Spring属性赋值,下面大家一起来学习吧。

一、@Value注解

Person的属性上使用@Value注解指定注入值

public class Person {
    
    @Value("#{20-2}")     //SpEL表达式 #{}
    private Integer id;
    
    @Value("张三")        //基本数据类型
    private String name;
}

配置类

@Configuration
public class MainConfigOfPropertyValues {

    @Bean
    public Person person(){
        return new Person();
    }
}

测试

 @Test
    public void testValues(){
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);

        String[] beanDefinitionNames = context.getBeanDefinitionNames();

        for (String beanName : beanDefinitionNames){
            System.out.println(beanName);
        }

        Person person = (Person) context.getBean("person");

        System.out.println(person);
    }

输出结果:

在这里插入图片描述

二、@PropertySource加载外部配置文件

配置类加上@PropertySource注解,引入外部配置文件

@PropertySource({"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {

    @Bean
    public Person person(){
        return new Person();
    }
}

使用${属性值}注入属性值

public class Person {

    @Value("#{20-2}")     //SpEL表达式 #{}
    private Integer id;

    @Value("张三")        //基本数据类型
    private String name;
    
    @Value("${person.age}")     //使用外部配置文件注入属性值
    private Integer age;
}

输出结果:

在这里插入图片描述

因为配置文件中的值默认都加载到环境变量中,所有还可以通过环境变量来获取配置文件中的值

 @Test
    public void testValues(){
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);

        String[] beanDefinitionNames = context.getBeanDefinitionNames();

        for (String beanName : beanDefinitionNames){
            System.out.println(beanName);
        }

        Person person = (Person) context.getBean("person");

        System.out.println(person);

        Environment environment = context.getEnvironment();

        String age = environment.getProperty("person.age");
        System.out.println("age = " + age);

    }

输出结果:

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们