Getting rid of getBean in a stand-alone Spring java Spring application (no web application, no container)

In web applications we really do not need to do.

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
ctx.getBean("beanId");

because it’s common practice to upload context files and inject all beans with dependencies using ContextLoaderServlet in web.xml like this.

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring-context.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- or use the ContextLoaderServlet instead of the above listener
<servlet>
  <servlet-name>context</servlet-name>
  <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
--> 

However, in a standalone java application without a container, I do ctx.getBean ("xyz"); . Is there a clean way to do this? I could not find an example on the Internet.

I checked .. Simple Spring, using ClasspathApplicationContext for standalone applications, how to reuse? which talks about using SingletonBeanFactoryLocator , but ultimately uses context.getBean ().

ServiceLocatorFactoryBean, - beans .

( beans) () Java, beans .

:

public interface IReader {
    public String read();
}

public class TextFileReader implements IReader {

    private StringBuilder builder = null;
    private Scanner scanner = null;

    public TextFileReader(String fileName) throws FileNotFoundException {
        scanner = new Scanner(new File(fileName));
        builder = new StringBuilder();
    }

    public String read() {
        while (scanner.hasNext()) {
            builder.append(scanner.next());
            builder.append(",");
        }
        return builder.toString();
    }
}



 public class SpringNoConextDataReaderClient {

    private IReader reader = null;

    public void setReader(TextFileReader reader) {
        this.reader = reader;
    }

    private String fetchDataOne() {
        return reader.read();
    }

    private String fetchDataTwo() {
        return reader.read();
    }

    public static void main(String[] args) {

        final ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        String fetchedData = context.getBean(SpringNoConextDataReaderClient.class).fetchDataOne(); // <-- reader is injected as TextFileReader in fetchDataOne which reads the file

        SpringNoConextDataReaderClient client = new SpringNoConextDataReaderClient();
        client.fetchDataOne(); // <--  reader is null and throws NPE, probably its lifetime ended with previous call?

        System.out.println("Example 1.1: Got data without context: " + fetchDataOne);
    }

}

spring -context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <bean id="reader" class="com.himalay.spring.core.basic.readers.TextFileReader">
        <constructor-arg value="src/main/resources/data.txt" />
    </bean>

    <bean id="springNoConextDataReaderClient" class="com.himalay.spring.core.basic.SpringNoConextDataReaderClient">
        <property name="reader"><ref bean = "reader" /></property>
    </bean>

</beans>

.

+5
1

ApplicationContext bean. bean Spring @Autowired .., getBean. , bean getBean, bean . - :

@Component
public class Main
{
    @Autowired
    protected MyDependencyClass2 someClass1;
    @Autowired
    protected MyDependencyClass2 someClass2;
    // ...
    // or if you need an entity manager
    @PersistenceContext
    protected EntityManager em;
    // etc.

    protected void mainInternal(String[] args)
        throws Exception
    {
        // do everything here
        // all dependencies are initialized
        // ...
    }

    public static void main(String[] args)
        throws Exception
{
        // Bootstrap Spring and let it create and configure beans.
        final ApplicationContext context =
            new ClassPathXmlApplicationContext("spring-context.xml");
        context.getBean(Main.class).mainInternal(args);
    }
}

. , getBean () getBean (String, Class), Class<T>.


new Main(), . Spring , new, , . Spring. , beans, .. , new.

, main mainInternal, . main, , .. , Spring, , Spring (, @Autowired), , , -.

, : beans, main. , mainInternal .


: . , Spring , , new.

SpringNoConextDataReaderClient client = new SpringNoConextDataReaderClient();

client Spring, . : , Spring ?

, . Spring usin . , . ( , HTTP- HTTP, .) , , .

, Spring , IReader. IReader , , , . :

  • singleton bean, IReader ,

    public class TextFileReaderProvider {
        public IReader createReader() { ... }
    }
    
  • SpringNoConextDataReaderClient

    public class SpringNoConextDataReaderClient {
        @Autowired
        protected TextFileReaderProvider readerProvider;
    
        public SomeResult doMyComputation() {
            IReader r = readerProvider.createReader();
            try {
                // compute the result
                return theResult;
            } finally {
                r.close();
            }
        }
    }
    

    ( @Autowired XML).

  • main Spring SpringNoConextDataReaderClient doMyComputation() .

, , concurrency.

+8

All Articles