方式1:使用@Autowired 构造方法
@Component
public class StaticServiceBean {
private static ServiceBean serviceBean;
@Autowired
public StaticServiceBean(ServiceBean serviceBean) {
StaticServiceBean.serviceBean = serviceBean;
}
public static void call() {
serviceBean.toString();
}
public static ServiceBean getServiceBean() {
return serviceBean;
}
}
方式2:使用@Autowired Setter方法
@Component
public class StaticServiceBean {
private static ServiceBean serviceBean;
public static ServiceBean getServiceBean() {
return serviceBean;
}
@Autowired
public static void setServiceBean(ServiceBean serviceBean) {
StaticServiceBean.serviceBean = serviceBean;
}
}
方式3:使用ApplicationContextWare
@Component
public class ServiceHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ServiceBean getServiceBean() {
return applicationContext.getBean(ServiceBean.class);
}
}
方式4:使用@Autowired+@PostContruct
@Component
public class StaticServiceBean {
private static ServiceBean staticServiceBean;
@Autowired
private ServiceBean serviceBean;
@PostConstruct
public void init() {
StaticServiceBean.staticServiceBean = serviceBean;
}
}