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 autowiring 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 autowiring mechanism isn't created yet.
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 autowiring mechanism isn't created yet.
If we want to use spring bean ref in static methods we need to use ApplicationContextAware interface and override setApplicationContext() and make context object as static.
The @Autowired annotation in spring automatically injects the dependent beans into the associated references of a POJO class. This annotation will inject the dependent beans by matching the data-type (i.e. Works internally as Autowiring byType).
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
You can't @Autowired
a static field. But there is a tricky skill to deal with this:
@Component public class StatisticLogger { private static Dao dao; @Autowired private Dao dao0; @PostConstruct private void initStaticDao () { dao = this.dao0; } }
In one word, @Autowired
a instance field, and assign the value to the static filed when your object is constructed. BTW, the StatisticLogger
object must be managed by Spring as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With