简体   繁体   中英

Java Spring Boot properties

@Service
public class LocationServiceImpl implements LocationService {

    @Value("${geoip.useId}")
    public int userId;

    @Value("${geoip.licenseKey}")
    public String licenseKey;



    private WebServiceClient client = new WebServiceClient.Builder(userId, licenseKey).build();


    @Override
    public Location getInfoByIp(String ip) {
        Location location = new Location(ip);

        try{

            InetAddress ipAddress = InetAddress.getByName(ip);

            CountryResponse response = client.country(ipAddress);
            Country country = response.getCountry();

            location.setIsoCode(country.getIsoCode());
            location.setName(country.getName());
        } catch (IOException | GeoIp2Exception ex) {
            ex.printStackTrace();
        }
        return location;
    }
}

When i run application, 'client' have default 'userId' and 'licenseKey'. But if this line move to method 'getInfoByIp' - all is ok. How to get values outside the method?

Also not work:

@Service
public class LocationServiceImpl implements LocationService {
    private int userId;
    private String licenseKey;

    @Autowired
    public LocationServiceImpl(@Value("${geoip.useId}") int userId,
                               @Value("${geoip.licenseKey}") String licenseKey) {
        this.userId = userId;
        this.licenseKey = licenseKey;
    }

    private WebServiceClient client = new WebServiceClient.Builder(userId, licenseKey).build();

    @Override
    public Location getInfoByIp(String ip) {

...

Are there any other ideas? I have no more ideas (

Create a method init with the annotation @PostConstruct with your client initialization inside.

@PostConstruct
public void init(){
    client = new WebServiceClient.Builder(userId, licenseKey).build();
}

See here for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM