无法使用 @Value 在 Springboot 的 application.yaml 中读取值。

huangapple go评论98阅读模式
英文:

Not able to read values using @Value in application.yaml in Springboot

问题

  1. 我正在使用Spring Boot - 2.3.3.RELEASEapplication.yaml中有一些值我正在尝试使用@Value注解将它们注入到类中但出于某些原因它们没有被加载结果应该是在SendPhoneByPhoneNumbers.java我们应该能够从application.yaml中读取notificationServiceURL
  2. 注意- 我正在使用工厂和策略模式该项目将被其他项目用作库以导入并使用服务层公开的方法
  3. 这是文件夹结构https://i.stack.imgur.com/jpbNj.jpg
  4. 我正在尝试通过以调试模式运行Demo.java来查看实际值的外观
  5. application.yaml

notificationService:
url: "https://someURL.com"

  1. Demo.java

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@SpringBootApplication
public class Demo {

  1. public static void main(String[] args) {
  2. SpringApplication.run(Demo.class, args);
  3. String title="Title";
  4. String message="message";
  5. List<String> phoneNumbers = new ArrayList<>();
  6. phoneNumbers.add("333-222-1111");
  7. PhoneService phoneService = new PhoneService();
  8. phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
  9. }

}

  1. PhoneService.java

@Service
public class PhoneService {

  1. PhoneServiceImpl notificationServiceImpl = new PhoneServiceImpl();
  2. public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
  3. notificationServiceImpl.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
  4. }

}

  1. PhoneServiceImpl.java

@Slf4j
@Component
public class PhoneServiceImpl {

  1. @Value("${notificationService.url}")
  2. String url;
  3. public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
  4. PhoneContext phoneContext = new PhoneContext(new SendPhoneByPhoneNumbers(url));
  5. phoneContext.notify(title, message, phoneNumbers);
  6. }

}

  1. PhoneContext.java

public class PhoneContext {

  1. private PhoneStrategy phoneStrategy;
  2. public PhoneContext(PhoneStrategy phoneStrategy){
  3. this.phoneStrategy = phoneStrategy;
  4. }
  5. public void notify(String title, String message, List<String> employees){
  6. phoneStrategy.sendNotification(title, message, employees);
  7. }

}

  1. PhoneStrategy.java

public interface PhoneStrategy {

public void sendNotification(String title, String message, List listOfEmployeeIdGroupNamePhoneNumbers);
}

  1. SendPhoneByPhoneNumbers.java

@Slf4j
public class SendPhoneByPhoneNumbers implements PhoneStrategy {

  1. RestTemplate restTemplate;
  2. String notificationServiceURL;
  3. BuildHttpRequest buildHttpRequest;
  4. public SendPhoneByPhoneNumbers(String notificationServiceURL) {
  5. this.notificationServiceURL = notificationServiceURL;
  6. this.restTemplate = new RestTemplate();
  7. this.buildHttpRequest = new BuildHttpRequest();
  8. }
  9. @Async
  10. public void sendNotification(String title, String message, List<String> phoneNumbers) {
  11. SmsMessage smsMessage= new SmsMessage(title, message, phoneNumbers, Collections.emptyList(), Collections.emptyList());
  12. try {
  13. HttpHeaders headers = new HttpHeaders();
  14. headers.set("idToken", buildHttpRequest.getNewToken());
  15. HttpEntity<SmsMessage> newRequest = new HttpEntity<>(smsMessage, headers);
  16. restTemplate.postForObject(notificationServiceURL + "/someUrl", newRequest, String.class);
  17. } catch (Exception e) {
  18. log.error(e.getMessage());
  19. }
  20. }

}

  1. 此外,如果您对修改代码/结构以使其更好的方式有任何建议,请务必提出。
  2. 提前致谢。
英文:

I'm using Spring boot - 2.3.3.RELEASE. There are some values in application.yaml which I'm trying to inject in the classes using @Value annotation. But for some reason, they are not loading up. The result should be that, in SendPhoneByPhoneNumbers.java, we should be able to read notificationServiceURL from application.yaml.

Note- I'm using Factory and Strategy pattern. This project is going to be used as a Library for other projects to import and use the methods exposed by Service layer.

Here is the folder structure: https://i.stack.imgur.com/jpbNj.jpg
I'm trying to test by running Demo.java in Debug mode to see how the actual values looks like.

application.yaml

  1. notificationService:
  2. url: &quot;https://someURL.com&quot;

Demo.java

  1. @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
  2. @SpringBootApplication
  3. public class Demo {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Demo.class, args);
  6. String title=&quot;Title&quot;;
  7. String message=&quot;message&quot;;
  8. List&lt;String&gt; phoneNumbers = new ArrayList&lt;&gt;();
  9. phoneNumbers.add(&quot;333-222-1111&quot;);
  10. PhoneService phoneService = new PhoneService();
  11. phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
  12. }
  13. }

PhoneService.java

  1. @Service
  2. public class PhoneService {
  3. PhoneServiceImpl notificationServiceImpl = new PhoneServiceImpl();
  4. public void sendNotificationByPhoneNumbers(String title, String message, List&lt;String&gt; phoneNumbers) {
  5. notificationServiceImpl.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
  6. }
  7. }

PhoneServiceImpl.java

  1. @Slf4j
  2. @Component
  3. public class PhoneServiceImpl {
  4. @Value(&quot;${notificationService.url}&quot;)
  5. String url;
  6. public void sendNotificationByPhoneNumbers(String title, String message, List&lt;String&gt; phoneNumbers) {
  7. PhoneContext phoneContext = new PhoneContext(new SendPhoneByPhoneNumbers(url));
  8. phoneContext.notify(title, message, phoneNumbers);
  9. }
  10. }

PhoneContext.java

  1. public class PhoneContext {
  2. private PhoneStrategy phoneStrategy;
  3. public PhoneContext(PhoneStrategy phoneStrategy){
  4. this.phoneStrategy = phoneStrategy;
  5. }
  6. public void notify(String title, String message, List&lt;String&gt; employees){
  7. phoneStrategy.sendNotification(title, message, employees);
  8. }
  9. }

PhoneStrategy.java

  1. public interface PhoneStrategy {
  2. public void sendNotification(String title, String message, List&lt;String&gt; listOfEmployeeIdGroupNamePhoneNumbers);
  3. }

SendPhoneByPhoneNumbers.java

  1. @Slf4j
  2. public class SendPhoneByPhoneNumbers implements PhoneStrategy {
  3. RestTemplate restTemplate;
  4. String notificationServiceURL;
  5. BuildHttpRequest buildHttpRequest;
  6. public SendPhoneByPhoneNumbers(String notificationServiceURL) {
  7. this.notificationServiceURL = notificationServiceURL;
  8. this.restTemplate = new RestTemplate();
  9. this.buildHttpRequest = new BuildHttpRequest();
  10. }
  11. @Async
  12. public void sendNotification(String title, String message, List&lt;String&gt; phoneNumbers) {
  13. SmsMessage smsMessage= new SmsMessage(title, message, phoneNumbers, Collections.emptyList(), Collections.emptyList());
  14. try {
  15. HttpHeaders headers = new HttpHeaders();
  16. headers.set(&quot;idToken&quot;, buildHttpRequest.getNewToken());
  17. HttpEntity&lt;SmsMessage&gt; newRequest = new HttpEntity&lt;&gt;(smsMessage, headers);
  18. restTemplate.postForObject(notificationServiceURL + &quot;/someUrl&quot;, newRequest, String.class);
  19. } catch (Exception e) {
  20. log.error(e.getMessage());
  21. }
  22. }
  23. }

Also, if you guys have any suggestions on modifying the code/structure in an way to make it better, please do suggest.

Thanks in advance.

答案1

得分: 1

  1. PhoneService phoneService = new PhoneService();

由于您使用的 PhoneService 不是 Spring 容器中的托管bean,所以值没有被注入。

代码改进和修复

  1. String title = "Title";
  2. String message = "message";
  3. List<String> phoneNumbers = new ArrayList<>();
  4. phoneNumbers.add("333-222-1111");
  5. // PhoneService phoneService = new PhoneService();
  6. phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);

将此代码移动到实现了 CommandLineRunnerApplicationRunner 接口的类中,并覆盖相应的 run() 方法。在该类中,您可以使用 @Autowired 注入 PhoneService,而不是手动实例化它。另外请注意,您需要在这个类上标记 @Component 注解。

其他建议的小改动:

  1. 您可以将 SendPhoneByPhoneNumbers 类设置为单例。如果有多个实现,请使用 @Qualifier
  2. RestTemplateBuildHttpRequest 都可以使用 @Bean 注解创建。
  3. 由于您正在使用 lombok,考虑使用 @RequiredArgsConstructor 也是一个选择。
英文:
  1. PhoneService phoneService = new PhoneService();

Since PhoneService that you are using is not a managed bean by spring container, the values are not being injected.

Code Improvement and FIX

  1. String title=&quot;Title&quot;;
  2. String message=&quot;message&quot;;
  3. List&lt;String&gt; phoneNumbers = new ArrayList&lt;&gt;();
  4. phoneNumbers.add(&quot;333-222-1111&quot;);
  5. // PhoneService phoneService = new PhoneService();
  6. phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);

Move this code to a class implementing CommanLineRunner or ApplicationRunner and override corresponding run(). In this class, you could @Autowire PhoneService rather than manually instantiating it. Also note that you have to mark this class with @Component

Other minor suggested changes:

  1. You can make SendPhoneByPhoneNumbers class a singleton. If there are multiple implementions, use @Qualifier
  2. Both RestTemplate and BuildHttpRequest could be created using @Bean annotation.
  3. Since you are using lombok, using @RequiredArgsConstructor could also be considered.

huangapple
  • 本文由 发表于 2020年10月14日 02:36:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64341203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定