简体   繁体   English

如何在另一个类中使用值注释?

[英]How can I use Value Annotations in another class?

How can I get my value here and use it in another class? 我如何在这里获得自己的价值并将其用于其他课程? I wanted to create a class that handles all the @Value annotations then the other classes can get those values from this class. 我想创建一个处理所有@Value批注的类,然后其他类可以从此类中获取这些值。 I will change from a main class to a new class once I learn how to get the values from another class 一旦我学会了如何从另一个班级获得价值,我将从一个主要班级转变为一个新班级

How can I get these variables 我如何获得这些变量

@Configuration
@ComponentScan
@EnableAutoConfiguration
public  class WebProperties {

       @Value("${Application}")
        private String app;      
        @Value("${APP_MEMORY_GREP_FOLDERS_APP}")
        private String appFolder;        
        @Value("${APP_MEMORY_GREP_FOLDERS_OPT}")
        private String optFolder;
      //getters and setters
}}

To print into the main class 打印到主班

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

    @Value("${Application}")
    private String app;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @PostConstruct
    public void postConstruct() {
        System.out.print("SampleApplication started: " + app);
    }
}

Without having to call @Value all over again 不必再次调用@Value

You can create a new properties class annotated with @Configuration. 您可以创建一个用@Configuration注释的新属性类。 There you annotate your Fields with @Value with all the properties you want. 在那里,您可以使用@Value注释所需的所有属性。 This class can be autowired in all other spring component Classes where the properties are needed. 可以在需要属性的所有其他弹簧组件类中将该类自动装配。

This is the Configuration class where I map the properties of my application.properties file: 这是Configuration类,在其中映射了application.properties文件的属性:

@Configuration
public class MyProperties{

    @Value("{my.property}")
    public String  myProperty;
}

It can be used as follows: 可以如下使用:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

@Autowired
private MyProperties props;

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@PostConstruct
public void postConstruct() {
    System.out.print("Print my property: " + props.myProperty);
}
}

This works for me. 这对我有用。 Hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM