【问题标题】:Getting null in Environment variable在环境变量中获取 null
【发布时间】:2018-09-11 05:38:02
【问题描述】:
@Configuration  
public class CustomRemoteTokenService implements ResourceServerTokenServices {

    private static final Logger logger = LoggerFactory.getLogger(CustomRemoteTokenService.class);

    @Resource
    Environment environment;

    private RestOperations restTemplate;

    private String checkTokenEndpointUrl;

    private String clientId;

    private String clientSecret;

    private String tokenName = "token";

    private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();

    @Autowired
    public CustomRemoteTokenService() {
        restTemplate = new RestTemplate();
        ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            // Ignore 400
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != 400
                        && response.getRawStatusCode() != 403 /* && response.getRawStatusCode() != 401 */) {
                    super.handleError(response);
                }
            }
        });
    }

    public void setRestTemplate(RestOperations restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void setCheckTokenEndpointUrl(String checkTokenEndpointUrl) {
        this.checkTokenEndpointUrl = checkTokenEndpointUrl;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) {
        this.tokenConverter = accessTokenConverter;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken)
            throws AuthenticationException, InvalidTokenException, GenericException {

        /*
         * This code needs to be more dynamic. Every time an API is added we have to add
         * its entry in the if check for now. Should be changed later.
         */
        HttpServletRequest request = Context.getCurrentInstance().getRequest();
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
        formData.add(tokenName, accessToken);
        formData.add("api", environment.getProperty("resource.api"));  
       /* formData.add("api", "5b64018880999103244f1fdd");*/

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
        Map<String, Object> map = null;
        try {
            map = postForMap(checkTokenEndpointUrl, formData, headers);
        } catch (ResourceAccessException e) {
            logger.error("Socket Exception occured at " + System.currentTimeMillis() + "for client_id :  " + clientId);

            GenericException ge = new GenericException(
                    "Could not validate your access token. If this occurs too often please contact MapmyIndia support at apisupport@mapmyindia.com");
            ge.setHttpErrorCode(504);
            ge.setOauthError("Access Token validation failed");
            throw ge;
        }

        if (map.containsKey("error")) {
            logger.error("check_token returned error: " + map.get("error") + " for client id : " + clientId);
            String temp = map.get("error").toString();
            GenericException ge = new GenericException(map.get("error_description").toString());
            ge.setHttpErrorCode(Integer.parseInt(map.get("responsecode").toString()));
            ge.setOauthError(temp);

            switch (temp) {
                case "invalid_token":
                    throw new InvalidTokenException(accessToken);
                default:
                    throw ge;
            }
        }

        Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
        return tokenConverter.extractAuthentication(map);
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        throw new UnsupportedOperationException("Not supported: read access token");
    }

    private String getAuthorizationHeader(String clientId, String clientSecret) {
        String creds = String.format("%s:%s", clientId, clientSecret);
        try {
            return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Could not convert String");
        }
    }

    private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers)
            throws RestClientException {
        if (headers.getContentType() == null) {
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        }
        @SuppressWarnings("rawtypes")
        Map map = restTemplate.exchange(path, HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
        @SuppressWarnings("unchecked")
        Map<String, Object> result = map;
        return result;
    }
}
  1. 我自动连接 Environment 并得到 null environment.getProperty("resource.api");

  2. 它总是返回 null 但在另一个类中我自动连接 Environment 并成功地从属性中检索值。

【问题讨论】:

  • 环境iteslf是否为空?还是 environment.getProperty("resource.api") 返回 null?
  • 尝试使用@Autowired 注释而不是@Resource 也尝试从环境中获取属性映射并检查它是否包含您的变量。
  • environment.getProperty("resource.api") 返回 null。@Abdul Mohsin
  • 使用@resource 也返回 null@Kamil W.
  • 您的属性文件是放在 /resources 文件夹下吗?您的属性文件的名称是什么

标签: java spring spring-mvc spring-data-jpa


【解决方案1】:

您必须采取以下步骤:

1.注册属性

您需要通过@PropertySource("classpath:foo.properties") 将您的属性文件注册为:

@Configuration
@PropertySource("classpath:foo.properties")
public class CustomRemoteTokenService implements ResourceServerTokenServices  {
    //...
}

2.注入属性

使用Environment API 获取属性的值:

@Autowired
private Environment env;

【讨论】:

  • 这个类在请求到达控制器之前被调用
  • 你的属性文件在哪里?
  • 最初它在 WEB-INF 中,然后我尝试了 @PropertySource("WEB-INF/application.properties")。有了这个 @PropertySource("classpath:foo.properties") ,我将它移动到资源文件夹
  • 能否更新您的问题并将您的项目文件夹层次结构包含为您的 IDE 的屏幕截图?
  • 用绝对路径重新检查@PropertySource("file:/path/to/application.properties")
猜你喜欢
  • 1970-01-01
  • 2013-08-10
  • 2013-03-02
  • 2017-02-19
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多