Java工作笔记-@Value注解的使用(可用于配置文件)
发布日期:2021-06-30 10:40:56 浏览次数:2 分类:技术文章

本文共 3033 字,大约阅读时间需要 10 分钟。

目录

 

 


 

 

基本概念

@Value:注入配置文件中的内容。只要是spring的注解类(service,compotent, dao等)中都可以。

@Component:泛指组件,当组件不好归类的时候,可以使用这个注解进行标注。

@AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。

所以必须是使用Spring或Spring Boot的注解类,就可以使用@Value注解。

下面是使用@Component进行的。刚好,单例模式也解决了,用框架是真的爽。

 

 

代码与实例

程序运行截图:不接参数时:

这个和application.properties一样

#自定义属性my.string=How are youmy.string2=How old are youredis.ip=127.0.0.1redis.port=6888redis.passwd=it1995

接如下参数:

java -jar demo-0.0.1-SNAPSHOT.jar --my.string=www.it1995.cn

运行截图如下:

关键代码如下:

JavaConf.java

package com.example.demo.conf;import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Data@Componentpublic class JavaConf {    @Value("${my.string}")    private String string1;    @Value("${my.string2}")    private String string2;    @Value("${redis.ip}")    private String redisIP;    @Value("${redis.port}")    private Integer redisPort;    @Value("${redis.passwd}")    private String redisPW;}

DemoApplication.java

package com.example.demo;import com.example.demo.conf.JavaConf;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DemoApplication implements CommandLineRunner {    public static void main(String[] args) {        SpringApplication.run(DemoApplication.class, args);    }    @Autowired    JavaConf javaConf;    @Override    public void run(String... args) throws Exception {        System.out.println("\n\n\n");        System.out.println("\n\n\n");        System.out.println("\n\n\n");        System.out.println("begin");        System.out.println(javaConf);        System.out.println("---------- 华丽的分割线 ----------");        System.out.println("\n\n\n");        System.out.println("\n\n\n");    }}

pom.xml

4.0.0
org.springframework.boot
spring-boot-starter-parent
1.5.21.RELEASE
com.example
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
1.7
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.18.10
org.springframework.boot
spring-boot-maven-plugin

 

 

程序打包下载

下载地址:

 

转载地址:https://it1995.blog.csdn.net/article/details/103388320 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:OllyDbg笔记-暴力破解简单判断程序(TraceMe.exe与简单Qt程序)
下一篇:Java工作笔记-Spring Boot上传图片并显示

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月06日 11时39分51秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章