在springboot应用程序中,无法从具有 "main "方法的类中读取属性文件中的属性以进行本地测试?

问题描述 投票:0回答:1

这个类不能从我的spring-boot应用程序的属性文件中读取数值--。

这是我项目的结构--

Project structure

我能够从这两个地方访问属性的值。application-dev.propertiesconfig.properties 在我 HomeController.java 类。

但我得到的值是 null 在我 ClientUtility.java 阶层

HomeControlller.java

@RestController
public class HomeController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private PropertyService propertyService;

    @Value("${customer.auth.key}")
    private  String customerAuthKey;

    @Autowired
    private EntityToDtoMapper mapper;

    @GetMapping(path="/customer/{id}",produces= {"application/xml"})
    public ResponseEntity<CustomerDto> getCustomer(@PathVariable("id")int id ,@RequestHeader("authKey") String language){
        System.out.println(propertyService.getKeytoAddCustomer());
        if(language.equals(customerAuthKey)) {
        CustomerDto customerDto=customerService.getCustomer(id);
        return new ResponseEntity<>(customerDto, HttpStatus.OK);
        }
        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }

ClientUtility.java

@Component
public class ClientUtility {

    @Value("${customer.auth.key}")
    private String customerAuthKey;

    @Autowired
    private PropertyService propertyService;

    public void getCustomers() {
        String url = "http://localhost:8080/customer/1";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        // add basic authentication header
        headers.set("authKey", "6AE-BH3-24F-67FG-76G-345G-AGF6H");
        System.out.println(customerAuthKey);
        System.out.println(propertyService.getKeytoAddCustomer());
        // build the request
        HttpEntity<CustomerDto> request = new HttpEntity<CustomerDto>(headers);

        ResponseEntity<CustomerDto> response = restTemplate.exchange(url, HttpMethod.GET, request, CustomerDto.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Request Successful.");
            System.out.println(response.getBody().getFirstName());
        } else {
            System.out.println("Request Failed");
            System.out.println(response.getStatusCode());
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ClientUtility clientUtility = new ClientUtility();
        clientUtility.getCustomers();

    }

}
}

产量

null
Exception in thread "main" java.lang.NullPointerException
    at com.spring.liquibase.demo.utility.ClientUtility.getCustomers(ClientUtility.java:33)
    at com.spring.liquibase.demo.utility.ClientUtility.main(ClientUtility.java:53)

应用程序.属性

spring.profiles.active=dev
logging.level.org.springframework.web=INFO
logging.level.com=DEBUG
local.server.port=8080

应用程序-设备.属性

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/liqbtest?useSSL=false
spring.datasource.username=liqbtest
spring.datasource.password=liqbtest

# Hibernate
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
customer.auth.key = 6AE-BH3-24F-67FG-76G-345G-AGF6H

配置.属性

auth.key.to.add.customer=6AE-BH3-24F-67FG-76G-345G-AGF6H

PropertyService.class

package com.spring.liquibase.demo.utility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:config.properties")
public class PropertyService {
    @Autowired
    private Environment env;

    public String getKeytoAddCustomer() {
        return env.getProperty("auth.key.to.add.customer");
    }
}
java spring spring-boot properties-file
1个回答
2
投票

这里当你使用ClientUtility clientUtility = new ClientUtility()时,它不会得到autowiredso属性不会被读取。所以我建议使用

//Inside main method
ApplicationContext applicationContext = SpringApplication.run(ClientUtility .class, args);
ClientUtility clientUtility = applicationContext.getBean(ClientUtility.class);     
clientUtility.getCustomers();

那应该可以了


0
投票

正如TomJava已经提到的那样,这是一个使用属性的好方法.另一个安全而稳妥的方法是将属性作为一个普通的java bean使用,然后利用它们。

例如

在application-dev.properties中, 使用

  • acme.enabled,默认值为false。
  • acme.remote-address,其类型可以由String胁迫。
  • acme.security.username,有一个嵌套的 "security "对象,其名称由属性名决定。特别是,那里根本没有使用returntype,可以是SecurityProperties。
  • acme.security.password。
  • acme.security.role,有一个String的集合,默认为USER。

package com.example;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("acme")
public class AcmeProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private final Security security = new Security();

    public boolean isEnabled() { ... }

    public void setEnabled(boolean enabled) { ... }

    public InetAddress getRemoteAddress() { ... }

    public void setRemoteAddress(InetAddress remoteAddress) { ... }

    public Security getSecurity() { ... }

    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        public String getUsername() { ... }

        public void setUsername(String username) { ... }

        public String getPassword() { ... }

        public void setPassword(String password) { ... }

        public List<String> getRoles() { ... }

        public void setRoles(List<String> roles) { ... }

    }
}

取自 今春文件


0
投票

使用@PropertySources Spring Annotation如下。

@Component
@PropertySources(value={@PropertySource("classpath:application-dev.properties")})
public class ClientUtility {

    @Value("${customer.auth.key}")
    private String customerAuthKey;

为什么不能通过Spring注解读取属性服务中的属性值?

PropertyService.class

package com.spring.liquibase.demo.utility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(value="classpath:config.properties")
public class PropertyService {

    @Value("${auth.key.to.add.customer}")
    private String authKey;

    public String getKeytoAddCustomer() {
        return authKey;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.