从pojo或singleton

时间:2016-09-04 11:12:43

标签: java spring spring-boot

我使用弹簧靴& amp;对于属性我已将application.properties放在src / main / resources

来自@Controllers& @Services,我能够阅读属性,但是从我的模型pojo&单身课程,我无法阅读这些数据。

我的@SpringBootApplication在com.vehicle&我没有覆盖@ComponentScan,所以我相信它应该读取所​​有底层包。

以下是代码:

application.properties

vehicle.lift.maxWeight=10
vehicle.lift.error.overWeight=Overweight

vehicle.battery.default=5.0
vehicle.battery.critical.limit=15
vehicle.walk.distance.error=Not able to move

WalkServiceImpl.java (能够从这里阅读)

package com.vehicle.prototype.service.impl;

@Service
public class WalkServiceImpl implements CapabilityService {

    @Value("${vehicle.walk.distance.error}")
    private String mDistanceError;

    @Override
    public void performTask(VehicleData vehicleData) {
        double distance = vehicleData.getWalkingDistance();
        double remainingBattery = vehicleData.getRemainingBattery();

        if (remainingBattery < distance) {
            vehicleData.setErrorMessage(mDistanceError);
            System.out.println(mDistanceError);
        } else {
            vehicleData.setRemainingBattery(remainingBattery - distance);
        }

        VehicleUtil.checkBatteryStatus(vehicleData);

    }

}

VehicleData.java (Pojo - 无法从此处阅读)

package com.vehicle.prototype.model;

public class VehicleData {

    private double walkingDistance;
    private double liftWeight;

    @Value("${vehicle.battery.default}")
    private double remainingBattery;

    // setters & getters ....

}

VehicleUtil.java (单身人士 - 无法从此处阅读)

package com.vehicle.prototype.utils;

public class VehicleUtil {

    private static VehicleUtil mInstance = null;
    private static Object mLock = new Object();

    @Value("${vehicle.battery.critical.limit}")
    private static double mCriticalLimit;

    @Value("${vehicle.battery.default}")
    private static double mTotalPower;

    @Value("${vehicle.battery.critical.warning}")
    private static String powerWarning;


    private VehicleUtil() {
        // empty private constructor.
    }

    public static VehicleUtil getInstance() {
        if (mInstance == null) {
            synchronized (mLock) {
                if (mInstance == null)
                    mInstance = new VehicleUtil();
            }
        }
        return mInstance;
    }

    public static void checkBatteryStatus(VehicleData vehicleData) {
        double criticalMark = (mCriticalLimit * 100.0f) / mTotalPower;
        if (vehicleData.getRemainingBattery() < criticalMark) {
            vehicleData.setBatteryCritical(Boolean.TRUE);
            System.out.println(powerWarning);
        } else {
            vehicleData.setBatteryCritical(Boolean.FALSE);
        }
    }

}

请告诉我如何解决这个问题。

谢谢

2 个答案:

答案 0 :(得分:2)

您需要将属性注入spring-managed bean。 你可以做的是将属性捆绑在这样的bean(see documentation

@ConfigurationProperties(prefix="vehicle")
public class VehicleProperties {
    @Value("${battery.critical.limit}")
    private double mCriticalLimit;

    @Value("${battery.default}")
    private double mTotalPower;

    @Value("${battery.critical.warning}")
    private String powerWarning;
}

然后,将Vehicle Properties注入您的服务并将它们传递给VehicleUtil:

public class WalkServiceImpl {
    @Autowired
    private VehicleProperties vehicleProperties;

    @Override
    public void performTask(VehicleData vehicleData) {
        ...
        VehicleUtil.checkBatteryStatus(vehicleProperties, vehicleData);
    }
}

更好的是,我会将VehicleUtil转换为托管bean

@Component
public class VehicleUtil {
    @Autowired
    private VehicleProperties vehicleProperties;
}

<强> VehicleData

我假设VehicleData是一些业务对象,是从客户端传递的,或者是您自己创建的,对于它们来说,它们是很多实例(不只是一个单例)。在这种情况下,将VehicleData转换为托管bean是没有意义的,它的外部依赖关系可以通过它的setter提供给它:

public class VehicleData {
    private double walkingDistance;
    private double liftWeight;
    private double remainingBattery;
    // setters & getters ....
}

答案 1 :(得分:0)

只有Spring控制的实例才能获取注入的属性值。

正如你有一个Spring应用程序,你不应该编写自己的单例逻辑而不是VehicleUtil的简单注释@Component。这也可以使任何用法更加可测试,因为你可以在注入util实例时在测试中模拟它。

您无法直接将值注入VehicleData pojo。属性值在运行时通常是常量,因此它只能是默认值。您应该在回购或服务中公开之前设置值,或者保留null并使用值而不是使用任何地方的非设置属性。