Using Spring from a custom backup application?

We use Spring to get all of our JDBC connections, as well as part of our persistence infrastructure. However, in order to write our own custom DB application (it should be normal, since we are not allowed to use DBAppender by default due to table name standards). How can I get a link to Spring beans / use autwire at this point from a custom Appender? I would rather stay in Spring instead of plain JDBC.

Custom Appender:

import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; public class CustomDBAppender extends AppenderBase<ILoggingEvent> { protected void append(ILoggingEvent event) { } } 
+6
source share
3 answers

This is how I solved the problem - I get the DataSource inside the appender start method via JNDI, and then create my JDBCTemplate. It worked great for me - no problem.

 public class MyAppender extends AppenderBase<ILoggingEvent> { private String _jndiLocation; private JDBCTemplate _jt; public void setJndiLocation(String jndiLocation) { _jndiLocation = jndiLocation; } @Override public void start() { super.start(); if (_jndiLocation == null) { throw new IllegalStateException("Must have the JNDI location"); } DataSource ds; Context ctx; try { ctx = new InitialContext(); Object obj = ctx.lookup(_jndiLocation); ds= (DataSource) obj; if (ds == null) { throw new IllegalStateException("Failed to obtain data source"); } _jt = new JDBCTemplate(ds); } catch (Exception ex) { throw new IllegalStateException("Unable to obtain data source", ex); } } @Override protected void append(ILoggingEvent e) { // log to database here using my JDBCTemplate instance } } 

I don’t know if you are facing the same problem, but I had to use a multi-step configuration (as described here ) because I received the SLF4J error message "log-log substitue logger" ( described here ).

+3
source

Your options are limited here, but you can use the SingletonBeanFactoryLocator stuff (see Spring's Guide, Adhesive Code and Evil Singleton ) and this SpringSource blog post .

+1
source

How I do this is to use AutowiredAnnotationBeanPostProcessor.

In your appender constructor, you will ask AutowiredAnnotationBeanPostProcessor to enter "this".

My comments at the end of this article detail the technique. The article talks about a similar method for auto-suspending Hibernate objects.

+1
source

Source: https://habr.com/ru/post/888356/


All Articles