Java 您可以将 @Autowired 与静态字段一起使用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1018797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:19:47  来源:igfitidea点击:

Can you use @Autowired with static fields?

javaspring

提问by

Is there some way to use @Autowiredwith static fields. If not, are there some other ways to do this?

有什么方法可以@Autowired与静态字段一起使用。如果没有,还有其他方法可以做到这一点吗?

采纳答案by skaffman

In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

简而言之,没有。您不能在 Spring 中自动连接或手动连接静态字段。您必须编写自己的逻辑来执行此操作。

回答by Jherico

Create a bean which you can autowire which will initialize the static variable as a side effect.

创建一个可以自动装配的 bean,它将初始化静态变量作为副作用。

回答by victor hugo

@Autowiredcan be used with setters so you could have a setter modifying an static field.

@Autowired可以与 setter 一起使用,因此您可以让 setter 修改静态字段。

Just one final suggestion... DON'T

只有一个最后的建议......不要

回答by JARC

You can achieve this using XML notationand the MethodInvokingFactoryBean. For an example look here.

您可以使用XML 表示法MethodInvokingFactoryBean. 有关示例,请参见此处

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approachbut this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

您应该尽可能使用spring 注入,因为这是推荐的方法,但这并不总是可行的,因为我相信您可以想象,因为并非所有东西都可以从 spring 容器中提取,或者您可能正在处理遗留系统。

Note testing can also be more difficult with this approach.

使用这种方法进行音符测试也会更加困难。

回答by Sedat Ba?ar

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

回答by ak-j

Init your autowired component in @PostConstruct method

在 @PostConstruct 方法中初始化您的自动装配组件

@Component
public class TestClass {
   private static AutowiredTypeComponent component;

   @Autowired
   private AutowiredTypeComponent autowiredComponent;

   @PostConstruct
   private void init() {
      component = this.autowiredComponent;
   }

   public static void testMethod() {
      component.callTestMethod();
   }
}

回答by Amol Kakade

private static UserService userService = ApplicationContextHolder.getContext().getBean(UserService.class);

回答by Ali

You can use ApplicationContextAware

您可以使用 ApplicationContextAware

@Component
public class AppContext implements ApplicationContextAware{
    public static ApplicationContext applicationContext;

    public AppBeans(){
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

then

然后

static ABean bean = AppContext.applicationContext.getBean("aBean",ABean.class);

回答by jozsef morrissey

DisclaimerThis is by no means standard and there could very well be a better spring way of doing this. None of the above answers address the issues of wiring a public static field.

免责声明这绝不是标准的,很可能有更好的春季方式来做到这一点。以上答案都没有解决连接公共静态字段的问题。

I wanted to accomplish three things.

我想完成三件事。

  1. Use spring to "Autowire" (Im using @Value)
  2. Expose a public static value
  3. Prevent modification
  1. 使用弹簧“自动装配”(我使用@Value)
  2. 公开一个公共静态值
  3. 防止修改

My object looks like this

我的对象看起来像这样

private static String BRANCH = "testBranch";

@Value("${content.client.branch}")
public void finalSetBranch(String branch) {
    BRANCH = branch;
}

public static String BRANCH() {
    return BRANCH;
}

We have checked off 1 & 2 already now how do we prevent calls to the setter, since we cannot hide it.

我们已经检查了 1 和 2 现在我们如何阻止对 setter 的调用,因为我们无法隐藏它。

@Component
@Aspect
public class FinalAutowiredHelper {

@Before("finalMethods()")
public void beforeFinal(JoinPoint joinPoint) {
    throw new FinalAutowiredHelper().new ModifySudoFinalError("");
}

@Pointcut("execution(* com.free.content.client..*.finalSetBranch(..))")
public void finalMethods() {}


public class ModifySudoFinalError extends Error {
    private String msg;

    public ModifySudoFinalError(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMessage() {
        return "Attempted modification of a final property: " + msg;
    }
}

This aspect will wrap all methods beginning with final and throw an error if they are called.

此方面将包装所有以 final 开头的方法,并在调用它们时抛出错误。

I dont think this is particularly useful, but if you are ocd and like to keep you peas and carrots separated this is one way to do it safely.

我认为这不是特别有用,但是如果您是强迫症并且喜欢将豌豆和胡萝卜分开,这是一种安全的方法。

ImportantSpring does not call your aspects when it calls a function. Made this easier, to bad I worked out the logic before figuring that out.

重要Spring 在调用函数时不会调用您的切面。使这更容易,糟糕的是我在弄清楚之前先弄清楚了逻辑。

回答by user7294900

Wanted to add to answers that auto wiring static field (or constant) will be ignored, but also won't create any error:

想要添加自动连接静态字段(或常量)将被忽略的答案,但也不会产生任何错误:

@Autowired
private static String staticField = "staticValue";