我解决了这个由下一招:
1-使用静态在AppConfig财产。
2-初始化它通过弹簧,当推土机使用默认的空构造它会找到的AppConfig有 值已经(其中弹簧之前分配给它)
这里是我用这个代码:
@Component //import org.springframework.stereotype.Component;
public class MyCustomDozerConverter extends DozerConverter<MyObject, String> {
private static AppConfig appConfig;
// dozer needs this constructor to create an instance of converter (so it's a mandatory constructor)
public MyCustomDozerConverter() {
super(MyObject.class, String.class);
}
@Autowired // Spring will pass appConfig to constructor
public MyCustomDozerConverter(AppConfig appConfig) {
this();
this.appConfig = appConfig;
}
@Override
public String convertTo(MyObject source, String destination) {
String myProperty = appConfig.getWhatever();
// business logic
return destination;
}
@Override
public MyObject convertFrom(String source, MyObject destination) {
// business logic
return null;
}
}
更新:另一种解决方案
另一个技巧是使用Spring ApplicationContextA洁具得到的getBean方法的单一对象:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
然后创建的AppConfig类中的静态方法,并返回一个bean的实例相匹配所需的类型:
import org.springframework.context.annotation.Configuration;
import com.tripbru.ms.experiences.ApplicationContextHolder;
@Configuration
public class AppConfig {
// Static method used to return an instatnce
public static AppConfig getInstance() {
return ApplicationContextHolder.getContext().getBean(AppConfig.class);
}
// Properties
}
然后调用它直接内推土机转换器AppConfig.getInstance();
public class MyCustomDozerConverter extends DozerConverter<MyObject, String> {
private static AppConfig appConfig;
public MyCustomDozerConverter() {
super(MyObject.class, String.class);
appConfig = AppConfig.getInstance(); // Here are we intializing it by calling the static method we created.
}
@Override
public String convertTo(MyObject source, String destination) {
String myProperty = appConfig.getWhatever();
// business logic
return destination;
}
@Override
public MyObject convertFrom(String source, MyObject destination) {
// business logic
return null;
}
}
什么是创建'MyCustomDozerConverter'实例?如果Spring没有这样做,那么依赖注入将无法工作。 –
是的,它不是创建实例的弹簧,它似乎是推土机正在做的,这就是为什么@Autowired不起作用,但我正在寻求建议或技巧来解决这个问题,找到了我? –