方式1:使用@Autowired 构造方法

  1. @Component
  2. public class StaticServiceBean {
  3. private static ServiceBean serviceBean;
  4. @Autowired
  5. public StaticServiceBean(ServiceBean serviceBean) {
  6. StaticServiceBean.serviceBean = serviceBean;
  7. }
  8. public static void call() {
  9. serviceBean.toString();
  10. }
  11. public static ServiceBean getServiceBean() {
  12. return serviceBean;
  13. }
  14. }

方式2:使用@Autowired Setter方法

  1. @Component
  2. public class StaticServiceBean {
  3. private static ServiceBean serviceBean;
  4. public static ServiceBean getServiceBean() {
  5. return serviceBean;
  6. }
  7. @Autowired
  8. public static void setServiceBean(ServiceBean serviceBean) {
  9. StaticServiceBean.serviceBean = serviceBean;
  10. }
  11. }

方式3:使用ApplicationContextWare

  1. @Component
  2. public class ServiceHolder implements ApplicationContextAware {
  3. private static ApplicationContext applicationContext;
  4. @Override
  5. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  6. this.applicationContext = applicationContext;
  7. }
  8. public static ServiceBean getServiceBean() {
  9. return applicationContext.getBean(ServiceBean.class);
  10. }
  11. }

方式4:使用@Autowired+@PostContruct

  1. @Component
  2. public class StaticServiceBean {
  3. private static ServiceBean staticServiceBean;
  4. @Autowired
  5. private ServiceBean serviceBean;
  6. @PostConstruct
  7. public void init() {
  8. StaticServiceBean.staticServiceBean = serviceBean;
  9. }
  10. }