【釘釘開發】關於@value和@autowired註解的使用和配置

resources文件夾下的application.properties

dingtalk.app_key=XXXXX
dingtalk.app_secret=XXXXX
dingtalk.agent_id=XXXXX
dingtalk.corp_id=XXXXX

com.dingtalk.bpm.config包下的AppConfig類

package com.dingtalk.bpm.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
//@Component
public class AppConfig {
    @Value("${dingtalk.app_key}")
    private String appKey;

    @Value("${dingtalk.app_secret}")
    private String appSecret;

    @Value("${dingtalk.agent_id}")
    private String agentId;

    @Value("${dingtalk.corp_id}")
    private String corpId;

    //省略他們的get、set函數
}

com.dingtalk.bpm.service包下的AccessTokenService類

package com.dingtalk.bpm.service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.bpm.config.AppConfig;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static com.dingtalk.bpm.config.UrlConstant.URL_GET_TOKEN;
//即https://oapi.dingtalk.com/gettoken

public class AccessTokenService {
    private static final Logger log = LoggerFactory.getLogger(AccessTokenService.class);
    @Autowired
    private AppConfig appConfig;

    public String getAccessToken() {
        DefaultDingTalkClient client = new DefaultDingTalkClient(URL_GET_TOKEN);
        OapiGettokenRequest request = new OapiGettokenRequest();
//        System.out.println("appkey:" + appConfig.getAppKey());

        request.setAppkey(appConfig.getAppKey());
        request.setAppsecret(appConfig.getAppSecret());
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
//            System.out.println(response.getBody());
        } catch (ApiException e) {
            log.error("getAccessToken failed", e);
        }

        return response.getAccessToken();
    }

【遇到的問題】@value能獲取到application.properties中的數據,但無法給各個成員變量賦值,只獲取到null

錯誤1 不能正確獲取使用了@AutoWired的對象

剛開始寫main方法測試時,直接new了一個accessTokenService對象,查閱資料後得知@autowired不能這樣做,但他喵的沒人寫應該怎麼做!!!正確方法如下,即使用ApplicationContext和ClassPathXmlApplicationContext獲取

public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccessTokenService accessTokenService = (AccessTokenService) applicationContext.getBean("accessTokenService");
        String accessToken = accessTokenService.getAccessToken();
        System.out.println("accessToken: " + accessToken);
}

注意引入的包:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

不要引入錯誤的包名,idea開始自動導入了其他的包導致第一句飄紅

錯誤2 spring.xml配置文件不知道怎麼寫

使用了Spring註解當然要配置了,但在百度“@value獲取失敗”、“@AutoWired使用”等問題時,資料中並沒有提到配置xml的問題,以下是spring.xml的配置內容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder ignore-unresolvable="true" location="classpath:application.properties" />
<!--        <context:annotation-config/>-->
        <context:component-scan base-package="com.dingtalk.bpm.config"/>
        <context:component-scan base-package="com.dingtalk.bpm.service"/>
        <bean id="accessTokenService" class="com.dingtalk.bpm.service.AccessTokenService"/>

</beans>

其中與@value獲取數據相關的配置信息爲:

<context:property-placeholder ignore-unresolvable="true" location="classpath:application.properties" />

與@autowired有關的配置信息爲:

<bean id="accessTokenService" class="com.dingtalk.bpm.service.AccessTokenService"/>

這樣就可以成功獲取到accessToken啦

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章