2

我想将三个属性( 、 和 )初始化companyTypescarrierLists全局cabinLevels变量:

@Controller
@RequestMapping("/backend/basic")
public class TicketRuleController {
    @Autowired
    private CarrierService carrierService;
    @Autowired
    private CabinLevelService cabinLevelService;
    @Autowired
    private CompanyTypeService companyTypeService;
    private List<DTOCompanyType> companyTypes = companyTypeService.loadAllCompanyTypes();
    private List<DTOCarrier> carrierLists = carrierService.loadAllCarriers();
    private List<DTOCabinLevel> cabinLevels = cabinLevelService.loadAllCabinLevel(); 
    ...
}

我怎样才能做到这一点?

4

2 回答 2

8

依赖注入完成后执行初始化的方法很少:您可以在某些方法上使用@PostConstruct注解。例如:

@PostConstruct
public void initialize() {
   //do your stuff
}

或者你可以使用 Spring 的InitializingBean接口。创建一个实现此接口的类。例如:

@Component
public class MySpringBean implements InitializingBean {


    @Override
    public void afterPropertiesSet()
            throws Exception {
       //do your stuff
    }
}
于 2013-08-29T07:26:15.770 回答
1

您应该能够添加一个构造函数进行初始化。

@Controller
@RequestMapping("/backend/basic")
public class TicketRuleController {

    private final CarrierService carrierService;
    private final CabinLevelService cabinLevelService;
    private final CompanyTypeService companyTypeService;

    private final List<DTOCompanyType> companyTypes;
    private final List<DTOCarrier> carrierLists;
    private final List<DTOCabinLevel> cabinLevels; 

    @Autowired
    public TicketRuleController(
            final CarrierService carrierService,
            final CabinLevelService cabinLevelService,
            final CompanyTypeService companyTypeService
        ) {
        super();
        this.carrierService = carrierService;
        this.cabinLevelService = cabinLevelService;
        this.companyTypeService = companyTypeService;
        companyTypes = companyTypeService.loadAllCompanyTypes();
        carrierLists = carrierService.loadAllCarriers();
        cabinLevels = cabinLevelService.loadAllCabinLevel();
    }

    // …
}
于 2013-08-29T06:26:15.117 回答