I hope this isn't too noob of a question, I'm still quite new to Spring. Can a bean class contain static methods? My initial thoughts is no because a static method is global, there's one instance per the entire application and threads to share but a bean might not be defined as such.

我希望这不是一个问题的太多菜鸟,我对Spring来说还是一个新手。 bean类可以包含静态方法吗?我最初的想法是否定的,因为静态方法是全局的,每个应用程序和共享的线程都有一个实例,但bean可能没有这样定义。

I tried searching for this question but couldn't find a clear answer.

我试着寻找这个问题,但找不到明确的答案。

2 个解决方案

#1


1

Yes,

A spring bean may have static methods too.

spring bean也可能有静态方法。

Using constructor @Autowired

使用构造函数@Autowired

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }

    public static int getThree(){
         return 3;
    }
}

You may also do it this way: Using @PostConstruct to hand value over to static field

您也可以这样做:使用@PostConstruct将值传递给静态字段

The idea here is to hand over a bean to a static field after bean is configured by spring.

这里的想法是在bean由spring配置之后将bean移交给静态字段。

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

source: @Autowired and static method

来源:@Autowired和静态方法

更多相关文章

  1. Java读取Unicode文件(UTF-8等)时碰到的BOM首字符问题,及处理方法
  2. java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
  3. java 和 JavaScript都可以在创建一个对象时,就可以通过这个对象调
  4. 有什么方法可以避免HibernateOptimisticLockingFailureException
  5. native方法的使用
  6. Java Quartz的使用方法,实现程序计时
  7. 将行计数器方法与字数统计方法相结合
  8. java基础:集合框架之Map(共性方法)
  9. JAVA中的反射只获取属性的get方法

随机推荐

  1. php解析url获取url中的参数值
  2. 简单记录PHP的超全局变量$_SERVER
  3. PHP+Redis 有序集合实现 24 小时排行榜实
  4. PHP面试题汇总(附答案)
  5. PHP is_file、file_exists、is_dir总结
  6. php 创建目录的几种方法
  7. PHP跨域问题解决方案
  8. 深度解析Nginx下的PHP框架路由实现
  9. php查询数据库并输出乱码
  10. PHP生成有背景的二维码图片