iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >详解Spring注解驱动开发之属性赋值
  • 930
分享到

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

2024-04-02 19:04:59 930人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

一、@Value注解 在Person的属性上使用@Value注解指定注入值 public class Person { @Value("#{20-2}")

一、@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);

    }

输出结果:

在这里插入图片描述

到此这篇关于详解spring注解驱动开发实现属性赋值的文章就介绍到这了,更多相关Spring注解驱动开发内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解Spring注解驱动开发之属性赋值

本文链接: https://www.lsjlt.com/news/126898.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作