Java – how to change property values at run time in spring

I need to change properties in the application at run time

My properties file has

hours.expired=12

My service

private int hoursExpiredPassword;

public void setHoursExpiredPassword(int hoursExpiredPassword) {
    this.hoursExpiredPassword = hoursExpiredPassword;
}

@Override
public ERequests checkRequest(String number,Date date) {
    PasswordResetRequest findedObject = passwordResetRequestDao.getObjectByElement(PasswordResetRequest.class,"requestId",number);
    if (findedObject == null){
        return ERequests.BAD_REQUEST;
    }else{
        long result = getDateDiff(findedObject.getRequestDate(),date,TimeUnit.HOURS);
        if(result >= hoursExpiredPassword){
            return ERequests.EXPIRED_REQUEST;
        }
    }
    return ERequests.CORRECT_REQUEST;
}

My spring XML configuration

<bean id="passwordResetRequestService" class="pl.lublin.example.services.servicesDAO.PasswordResetRequestService">
    <property name="passwordResetRequestDao" ref="passwordResetRequestDao"></property>
    <property name="hoursExpiredPassword" value="${hours.expired}"></property>
</bean>

Can I change this value in some way at run time?

Solution

Just separated from the XML configuration in 2017

@Service
public class PasswordResetRequestService {

@Value("${hours.expired:12}") 
private int hoursExpiredPassword;

@Autowired
private PasswordResetRequestDao passwordResetRequestDao;

public void setHoursExpiredPassword(int hoursExpiredPassword) {
    this.hoursExpiredPassword = hoursExpiredPassword;
}


@Override
public ERequests checkRequest(String number,TimeUnit.HOURS);
        if(result >= hoursExpiredPassword){
            return ERequests.EXPIRED_REQUEST;
        }
    }
    return ERequests.CORRECT_REQUEST;
   }

}

With @ value, you will extract hours. From the properties file Expired value. If there is no value, the default value is 12 You can also call sethoursexpired at runtime and set a new value and expose this function to your administrator

This is very convenient for one-time operation If you want the administrator to permanently change the password expiration time, I will continue to use hours in MySQL or the database you are using Expired value

Editor: answer fully valid @ Matt comments If this is the case, and turning to Java confining is not an option For custom behavior, you just need to automatically assemble XML defined beans in the service and execute any logic you want

@Autowired
private pl.lublin.zeto.zetoRA.services.servicesDAO.PasswordResetRequestService passwordResetRequestService;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>