简体   繁体   English

如何使用Spring在抽象类中注入静态方法的局部变量?

[英]How can I inject local variables of a static method inside an abstract class using Spring?

I'm new to Spring and ran into this problem.I tried using @Autowired on the method but it didnt work,on the variables I get the error "The annotation @Autowired is disallowed for this location" from eclipse. 我是Spring的新手,遇到了这个问题。我尝试在该方法上使用@Autowired,但没有成功,在变量上,我从Eclipse中收到错误消息“该位置不允许使用@Autowired注解”。 I have the required beans created in the xml. 我在xml中创建了所需的bean。

Below is the code,this method is inside an abstract class.. 下面是代码,此方法在抽象类内。

private static HttpResponse rawExecuteReqeust(HttpUriRequest request) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    ProxyInterface proxyI; // needs to be Injected
    User user; // needs to be Injected
    System.out.println("About to execute " + request.getMethod() + " request on        " 
        + request.getURI());
    if (proxyI.getProxyHost() != null && proxyI.getProxyPort() != 0) {
        if (user.getProxyUser() != null && user.getProxyPassword() != null) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyI.getProxyHost(), proxyI.getProxyPort()),
                    new UsernamePasswordCredentials(user.getProxyUser(), user.getProxyPassword()));
        }
        HttpHost proxy = new HttpHost(proxyI.getProxyHost(), proxyI.getProxyPort(), "http");
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    HttpResponse response = client.execute(request);
    return response;
}

(ps Im new to stackOverflow and hope I formatted the question properly :) ) (ps我是stackOverflow的新手,希望我正确格式化了问题:))

From the documentation of @Autowired 来自@Autowired的文档

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. 将构造函数,字段,setter方法或config方法标记为由Spring的依赖项注入工具自动装配。

As you see there is no local variables. 如您所见,没有局部变量。 So Eclipse is right. 因此,Eclipse是正确的。 And in Java you can not annotate local variables with any other annotation. 并且在Java中,您不能使用任何其他注释来注释局部变量。 It's not possible at all. 根本不可能。

So you have two options: 因此,您有两种选择:

Make field user and inject your user there. 使现场用户,然后将您的用户注入那里。

public class Test {
        @Autowired
        private User user;

        private HttpResponse rawExecuteReqeust(){
            // do something with field user
        }
    }

Make some kind of UserService which will provide you user objects 制作某种UserService,它将为您提供用户对象

public class Test {
    @Autowired
    private UserService userService;

    private HttpResponse rawExecuteReqeust(){
        User user = userService.getUser();
        // do something with local variable user
    }
}

All this very good covered is Spring documentation. 所有这些很好的内容都是Spring文档。 After reading it everything would be much more clear for you. 阅读后,一切对您来说都会更加清晰。

UPD: Turned out that with java 8 you CAN have annotations on your local variables. UPD:事实证明,使用Java 8,您可以在局部变量上添加注释。 I didn't see deep into it, but it won't help because spring doesn't use this type of target and most likely this annotations don't give you access to local variable value. 我没有深入了解它,但是它并没有帮助,因为spring不使用这种类型的目标,并且很可能该注释不能使您访问局部变量值。

UPD2 No, Spring doesn't allow you to inject dependencies into static fields. UPD2不,Spring不允许您将依赖项注入静态字段。 There are some workarounds like inject in setter and inside setter set static field, but they are evil and will mess you code up. 有一些解决方法,例如在setter和in setter set静态字段中注入,但是它们很邪恶,会使您的代码混乱。 So just make this method non static. 因此,只需将此方法设为非静态即可。 And sorry for static keyword in my examples, it was copy and paste and of course it wouldn't work with static method. 很抱歉在我的示例中使用static关键字,它是复制和粘贴,当然它不适用于static方法。

If it is possible for you to turn user and proxyI into static properties you can inject them by utilizing the MethodInvokingFactoryBean . 如果可以将userproxyI转换为静态属性,则可以使用MethodInvokingFactoryBean注入它们。 You will have to provide a static setter method. 您将必须提供静态的setter方法。 To give you an idea of the configuration: 让您对配置有所了解:

<bean name="staticHubInitializer" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="your.AbstractUtilClass.setStaticDependencies"/>
        <property name="arguments">
            <list>
                <ref bean="user"/>
                <ref bean="proxyI"/>
            </list>
       </property>
    </bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能调用Abstract类的非静态方法 - How can i call an non static method of Abstract class 如何使用 Spring 将属性值注入枚举或普通类的静态属性或方法? - How to Inject property values into a static property or method of an enum or normal class using Spring? 我可以使用Spring注入相同的类吗? - Can I inject same class using Spring? 如何使用基于Spring的单元测试模拟返回Servlet上下文的抽象类中可用的静态方法 - How to mock static method available in abstract class which returns servlet context using spring based unit test 如何从另一个类的静态方法获取抽象类的子类的实例? - How can I get an instance of a subclass of abstract class from a static method of another class? 为什么我在Java中的同一个类中没有抽象和静态方法 - Why can I not have an abstract and static method in the same class in Java 如何从Spring bean注入静态变量? - How to inject static variables from spring bean? 我们可以在抽象类中使用静态方法吗? - Can we use static method in an abstract class? 如何在 Spring-Boot 中注入静态类? - How to inject static class in Spring-Boot? Mocking a static 抽象 class 中的方法使用 Z4D1142CA816EAC3E33B383BC0B79B537 - Mocking a static Method in Abstract class using Mockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM