This is an Spring MVC project with Hibernate. I'm, trying to make a Logger class that, is responsible for inputting logs into database. Other classes just call proper methods with some attributes and this class should do all magic. By nature it should be a class with static methods, but that causes problems with autowiering dao object.
public class StatisticLogger {
@Autowired
static Dao dao;
public static void AddLoginEvent(LogStatisticBean user){
//TODO code it god damn it
}
public static void AddDocumentEvent(LogStatisticBean user, Document document, DocumentActionFlags actionPerformed){
//TODO code it god damn it
}
public static void addErrorLog(Exception e, String page, HashMap<String, Object> parameters){
ExceptionLogBean elb=new ExceptionLogBean();
elb.setStuntDescription(e);
elb.setSourcePage(page);
elb.setParameters(parameters);
if(dao!=null){ //BUT DAO IS NULL
dao.saveOrUpdateEntity(elb);
}
}
How to make it right? What should I do not to make dao object null? I know that I could pass it as a method parameter, but that isn't very good. I'm guessing that autowired can't work on static objects, because they are created to early to autowiering mechanism isn't created yet.
Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods.
I thought it'd worthy to mention it. – MaxouMask Jan 19 '17 at 9:42The method on which PostConstruct is applied MAY be public, protected, package private or private.
so I think initStaticDao() could beprivate
just so nobody has to see it when using code completion etc. – spoko Mar 27 '17 at 15:28bootstrap.yml
file. All the@values
are configured inCosmosConnection
class. Here is my codestatic CosmosConnection cosmos= new CosmosConnection(); @Autowired private CosmosConnection tcosmos; @PostConstruct public void init() { SupplierGetResponseFeed.cosmos = tcosmos; }
In the same class I have another method from where I am callingcosmos.connectToDB();
– Anand Deshmukh Apr 9 at 15:16