spring 加载构造函数时值为空

1cklez4t  于 2023-08-02  发布在  Spring
关注(0)|答案(4)|浏览(110)

在构造函数中不使用Properties,我看到@Value注解应该可以做到这一点。
它在我的另一个实现中工作,但在这里它不工作
控制器:

@Autowired
private Customer customer;

字符串
我的班级

@Service
public class Customer {

    /** The soap GW endpoint. */
    @Value("${soapGWEndpoint}")
    private String soapGWEndpoint;

    /** The soap GW app name. */
    @Value("${soapGWApplName}")
    private String soapGWAppName;

    /** The soap GW user. */
    @Value("${generic.user}")
    private String soapGWUser;

    /** The soap GW password. */
    @Value("${generic.user.password}")
    private String soapGWPassword;

    public Customer () {
        // All parameters are null:
        login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
    }
}


但它们在application.properties文件中。
为什么在这种情况下我不能使用@Value?

wlp8pajw

wlp8pajw1#

Spring不会注入preoperties的值,直到对象完全示例化(Spring要做的第一件事是调用构造函数,因为这是创建新对象的默认方式)。你应该在@PostConstruct方法中调用login(),这样Spring在初始化对象后自动调用它:

@Service
public class Customer {

    /** The soap GW endpoint. */
    @Value("${soapGWEndpoint}")
    private String soapGWEndpoint;

    /** The soap GW app name. */
    @Value("${soapGWApplName}")
    private String soapGWAppName;

    /** The soap GW user. */
    @Value("${generic.user}")
    private String soapGWUser;

    /** The soap GW password. */
    @Value("${generic.user.password}")
    private String soapGWPassword;

    public Customer () {
    }

    @PostConstruct
    public void init() {
      login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
    }
}

字符串

3gtaxfhh

3gtaxfhh2#

另一种选择是像这样使用构造函数注入

@Service
public class Customer {

  private String soapGWEndpoint;
  private String soapGWAppName;
  private String soapGWUser;
  private String soapGWPassword;

  @Autowired
  public Customer(@Value("${soapGWEndpoint}") String soapGWEndpoint,
                @Value("${soapGWApplName}") String soapGWAppName,
                @Value("${generic.user}") String soapGWUser,
                @Value("${generic.user.password}") String soapGWPassword) {
    this.soapGWEndpoint = soapGWEndpoint;
    this.soapGWAppName = soapGWAppName;
    this.soapGWUser = soapGWUser;
    this.soapGWPassword = soapGWPassword;
    login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
  }
}

字符串

fzsnzjdm

fzsnzjdm3#

你可以在对象初始化后使用@PostConstruct。请看一下我之前写的示例代码:

@Configuration
public class BrinkWebserviceConfig {

    private static final Logger LOG = LoggerFactory.getLogger(BrinkWebserviceConfig.class);

    private String accessToken;
    private String locationToken;
    private String domain;

    @Value("${brink.soap.settingsAPI}")
    String BRINK_SETTINGS_API;

    @Value("${brink.soap.sales2API}")
    String BRINK_SALES2_API;

    @Value("${brink.soap.orderingAPI}")
    String BRINK_ORDERING_API;

    @Value("${brink.soap.settings2API}")
    String BRINK_SETTINGS2_API;

    @PostConstruct
    public void init() {
        LOG.info("Loading the access and location tocken for using in the configuration and setting the clients URLs");

        loadCredentialsAndDomainURL();
        loadClientsAPI();
    }

    public ClientInterceptor brinkHeaderInterceptor(Logger LOG) {

        return new ClientInterceptorAdapter() {
            @Override
            public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
                TransportContext context = TransportContextHolder.getTransportContext();
                HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
                try {
                    connection.addRequestHeader("AccessToken", accessToken);
                    connection.addRequestHeader("LocationToken", locationToken);
                } catch (IOException e) {
                    LOG.error("header interceptor error", e);
                    return false;
                }

                return true;
            }
        };
    }

    private void loadCredentialsAndDomainURL() {

        String s = "src/test/resources/brink.properties";
        Resource r = new FileSystemResource(s);

        Properties props = new Properties();

        try {
            props.load(r.getInputStream());

//            accessToken = props.getProperty("token");
//            locationToken = props.getProperty("appId");

            accessToken = props.getProperty("password");
            locationToken = props.getProperty("username");
            domain = props.getProperty("domain1");

        } catch (IOException e) {
            LOG.error("We have an error for reading the access and location tokens for Brink web-service config");
        }
    }

    private void loadClientsAPI() {

        BRINK_SETTINGS_API = domain + BRINK_SETTINGS_API;
        BRINK_SALES2_API = domain + BRINK_SALES2_API;
        BRINK_ORDERING_API = domain + BRINK_ORDERING_API;
        BRINK_SETTINGS2_API = domain + BRINK_SETTINGS2_API;
    }
}

字符串
调用loadCredentialsAndDomainURL()`` and loadClientsAPI()methods, the object is ready and can read the property values from the application.properties ``文件时。

xn1cxnb4

xn1cxnb44#

问题是对象一初始化就抛出空指针异常

相关问题