0

This is first class:

@Service
public class ServiceA{

@Autowired
ServiceB serviceB;

String neededString;

public void methodSome(){
//uses neededString
}

}

This is second

@Service
public class ServiceB{

String neededString;

public void methodSome(){
//uses neededString
}
}

and i need to get the variable from another service:

neededString = thirdServiceToReturn();

Both classes need that neededString variable to do their own methods. I can get from 3. service in the method seperately or i can get with PostConstruct for each class.

But i want to get from a common place for both classes. Maybe from 2. class . I can try static but it wont be thread safe i guess.

The variable wont change for months maybe. It takes some values and returns from database. After some deploy, it can change so, it should get new one at some point.

I use Spring Boot also. What do you suggest?

Maybe a Constant class with @Bean and do the initializing there and then Autowired to second class? Like that: Is there any way to pass @Autowired variable to some other class in a Spring Boot application?

The variable will change in future. It is reading from database, which is derived with @cached so it will read from cache until the application is restarted or is deployed. Variable needs to be parametric, not hardcoded.

Static variable is not thread safe. I want to reach the solution. Thread safe.

asdasasd
  • 81
  • 1
  • 9
  • 1
    I don't understand the reason it needs to be threadsafe. All classes and instances are to share the same value. Also the value that is visible to all threads should change at the same time. – John Williams Mar 16 '23 at 16:52
  • @JohnWilliams yes, should change at same time. So, it needs to be thread safe? Can i use static? – asdasasd Mar 16 '23 at 16:57
  • 1
    Yes, use a static. neededString does **not** need to be thread safe, it needs to be the opposite. – John Williams Mar 16 '23 at 17:04
  • @JohnWilliams static string and initialize with postconstruct? – asdasasd Mar 16 '23 at 17:54
  • Yes, if it needs initialisation logic. – John Williams Mar 16 '23 at 18:01
  • @JohnWilliams methodSome() needs to use that variable. Both class needs that variable so at first, it needs to be initialized at somewhere. Maybe at another bean or postconstruct are the options i think. – asdasasd Mar 16 '23 at 18:16

1 Answers1

1

This is first class:

@Service
public class ServiceA{

@Autowired
ServiceB serviceB;

public static String neededString;

@PostConstruct
public void setupNeededString() {
    neededString = “”;
}

public void methodSome(){
//uses neededString
}

}

This is second

@Service
public class ServiceB{



public void methodSome(){
//uses ServiceA.neededString
}
}
John Williams
  • 4,252
  • 2
  • 9
  • 18