0

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.

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

Kevin
  • 3,209
  • 9
  • 39
  • 53
  • 1
    Of course a class **can** contain static methods. A better question is *should* it contain static methods. And there (as you note) a static method is global, and there's one instance per the entire applicate (that is, they are Singletons). As such, you must ensure any static methods are thread safe. – Elliott Frisch Dec 08 '17 at 01:53

2 Answers2

1

Yes,

A spring bean may have static methods too.

Using constructor @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

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

@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

Robert I
  • 1,509
  • 2
  • 11
  • 18
0

It can be contained.

@Service
public class TestService {

    @Autowired
    private TestDao testDao;

    public static void test(){
        System.out.println("test");
    }
}


@RestController
@RequestMapping("/api/")
public class TestController {

    @Autowired
    private TestService testService;

    @PostMapping("test")
    public String test(){
       TestService.test();
       return "ok";
    }
}
b.s
  • 2,409
  • 2
  • 16
  • 26