{"id":2326,"date":"2013-01-11T10:21:16","date_gmt":"2013-01-11T09:21:16","guid":{"rendered":"http:\/\/sahits.ch\/blog\/?p=2326"},"modified":"2013-01-11T10:21:16","modified_gmt":"2013-01-11T09:21:16","slug":"combining-standalone-application-with-spring","status":"publish","type":"post","link":"http:\/\/sahits.ch\/blog\/blog\/2013\/01\/11\/combining-standalone-application-with-spring\/","title":{"rendered":"Combining standalone application with Spring"},"content":{"rendered":"<p>When you are developing a standalone application, that you want to use with the SpringFramework, somewhere in your code you will have to load the application context. Potentially this results in chicken-egg problem, especially when you want to use a component in some class that is not a bean. This may have different causes:<\/p>\n<ul>\n<li>It is the main class, that is used to start up the application<\/li>\n<li>The constructor uses arguments that cannot be resolved with autowireing<\/li>\n<\/ul>\n<p>There are different approaches to solve this, the most elegant one I will demonstrate.<!--more-->Some brains storming produces the following approaches:<\/p>\n<ul>\n<li>Use of a factory class that can be used to initialize the no-bean class<\/li>\n<li>Using aspects to resolve the autowiring dependencies<\/li>\n<li>Initiate autowiring manually<\/li>\n<\/ul>\n<h2>The factory approach<\/h2>\n<p>While this is a simple solution, it is not entirely elegant. It involves the creation of a factory class as a bean which has the components wired in, that are needed to create the non-bean class and some static create method. However the fact that the factory is a bean is not exploited. It has to be declared as a bean so autowiring can take place.<\/p>\n<h2>Using Aspects<\/h2>\n<p>This is perhaps the most elegant solution from the view point of the application code, as the autowiring works as if it were a bean. On the downside the Aspect needs to be declared.<\/p>\n<p>If the constructor calls a init method, this can be intercepted. Unfortunately you can only intercept public methods with Spring AOP, as it is proxy based. Additionally to define the pointcut you should define a annotation for the class, so you can single out all the classes with an init method, which should be considered by this aspect.<\/p>\n<p>Using AspectJ for this seams the better solution, as then the pointcut can be defined on the level of the constructor. The actual code that has to be executed looks similar to the one in the manual case.<\/p>\n<h2>Initialize autowiring manually<\/h2>\n<p>The first question that pops up is, why would anyone do such a thing? Why not wire the dependencies manually:<\/p>\n<pre class=\"brush:java\">  private ComponentConsumer consumer; \/\/ &lt;== Spring main class\r\n\r\n  public Main(){\r\n    ApplicationContext context = new ClassPathXmlApplicationContext(\"applicationContext.xml\");\r\n    consumer = context.getBean(ComponentConsumer.class);\r\n  }<\/pre>\n<p>One answer is flexibility. If you have only one bean to wire both approaches are about the same. However if you have more, you get an additional line of code for each additional bean. The other point is expendability during time: when you want to add a dependency to another bean tomorrow, you will have to define the bean and its initialisation.<\/p>\n<p>But now let&#8217;s have a look at some code. First there are two beans one a Service and one a Component:<\/p>\n<pre class=\"brush:java\">package ch.sahits.test.spring.components;\r\n\r\nimport org.springframework.stereotype.Component;\r\n\r\n@Component\r\npublic class SimpleWriter {\r\n\r\n  public void sayHello() {\r\n    System.out.println(\"Hello Spring DI Component!\");\r\n  }\r\n}<\/pre>\n<pre class=\"brush:java\">package ch.sahits.test.spring.components;\r\n\r\nimport org.springframework.stereotype.Service;\r\n\r\n@Service\r\npublic class SimpleWriterService {\r\n\r\n  public void sayHello() {\r\n    System.out.println(\"Hello Spring DI service!\");\r\n  }\r\n}<\/pre>\n<p>Next is another Component, which consumes from these two writers:<\/p>\n<pre class=\"brush:java\">package ch.sahits.test.spring;\r\n\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.stereotype.Component;\r\n\r\nimport ch.sahits.test.spring.components.SimpleWriter;\r\nimport ch.sahits.test.spring.components.SimpleWriterService;\r\n\r\n@Component\r\npublic class ComponentConsumer {\r\n\r\n  @Autowired\r\n  private SimpleWriter component;\r\n  @Autowired\r\n  private SimpleWriterService service;\r\n\r\n  public void consume() {\r\n    component.sayHello();\r\n    service.sayHello();\r\n  }\r\n}<\/pre>\n<p>Now the really interesting part is the class containing the main method.<\/p>\n<pre class=\"brush:java\">package ch.sahits.test.spring;\r\n\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.beans.factory.config.AutowireCapableBeanFactory;\r\nimport org.springframework.context.ApplicationContext;\r\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\r\n\r\npublic class Main {\r\n  @Autowired\r\n  private ComponentConsumer consumer; \/\/ &lt;== Spring main class\r\n\r\n  public Main(){\r\n    ApplicationContext context = new ClassPathXmlApplicationContext(\"applicationContext.xml\");\r\n    AutowireCapableBeanFactory acbFactory = context.getAutowireCapableBeanFactory();\r\n    acbFactory.autowireBean(this);\r\n  }\r\n\r\n  public static void main(String[] args) {\r\n\r\n    Main main = new Main();\r\n    main.consumer.consume();\r\n  }\r\n}<\/pre>\n<p>The &#8218;miraculous&#8216; part happens in the constructor. Retrieving the application-context, getting an <a href=\"http:\/\/static.springsource.org\/spring\/docs\/3.0.x\/api\/org\/springframework\/beans\/factory\/config\/AutowireCapableBeanFactory.html\">AutowireCapableBeanFactory <\/a>and then tell the factory to resolve all autowired dependencies in this class. The ugly part here is the reference escape of this in the constructor.<\/p>\n<p>For completeness<\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\"?&gt;\r\n&lt;beans xmlns=\"http:\/\/www.springframework.org\/schema\/beans\"\r\n\txmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\r\n  xmlns:context=\"http:\/\/www.springframework.org\/schema\/context\"\r\n\txsi:schemaLocation=\"http:\/\/www.springframework.org\/schema\/beans \r\n                      http:\/\/www.springframework.org\/schema\/beans\/spring-beans.xsd\r\n                      http:\/\/www.springframework.org\/schema\/context \r\n                      http:\/\/www.springframework.org\/schema\/context\/spring-context-2.5.xsd\"&gt;\r\n\r\n  &lt;context:component-scan base-package=\"ch.sahits.test.spring\"\/&gt;\r\n\r\n&lt;\/beans&gt;<\/pre>\n<p>sake here the applicationContext.xml:<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When you are developing a standalone application, that you want to use with the SpringFramework, somewhere in your code you will have to load the application context. Potentially this results in chicken-egg problem, especially when you want to use a component in some class that is not a bean. This may have different causes: It &hellip; <a href=\"http:\/\/sahits.ch\/blog\/blog\/2013\/01\/11\/combining-standalone-application-with-spring\/\" class=\"more-link\"><span class=\"screen-reader-text\">\u201eCombining standalone application with Spring\u201c <\/span>weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,6],"tags":[273,272,270,271,269],"class_list":["post-2326","post","type-post","status-publish","format-standard","hentry","category-java","category-programmieren","tag-application-context","tag-autowire","tag-dependency-injection","tag-di","tag-spring"],"_links":{"self":[{"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/posts\/2326","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/comments?post=2326"}],"version-history":[{"count":2,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/posts\/2326\/revisions"}],"predecessor-version":[{"id":2328,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/posts\/2326\/revisions\/2328"}],"wp:attachment":[{"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/media?parent=2326"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/categories?post=2326"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sahits.ch\/blog\/wp-json\/wp\/v2\/tags?post=2326"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}