Multiple ways of initiating the same object using Spring's @Autowired

Viewed 22

I have one Spring project but it has two build configurations:

  1. WAR build to be run on a Tomcat container
  2. Standalone executable JAR

So I have separate context/servlet XMLs for each of them to tell how I want to initialise the beans.

  1. With the WAR build, I have something like this for my @Autowired annotations
    <context:component-scan base-package="com.package.my"/>
    
  2. With the standalone executable JAR, I have this instead
    <context:annotation-config/>
    

So here is the problem. I want to add a new class that extends the PrintStream class. Like this:

package com.package.my;
import java.io.PrintStream;
...
@Component
public class MyPrintStream extends PrintStream { ... }

However, I want to initialize MyPrintStream differently for WAR build and JAR build.

  • For WAR build, I want to initialize it in this fashion (if doing it without @Autowired):
    MyPrintStream myPrintStream = new PrintStream(new java.io.ByteArrayOutputStream(), true, java.nio.charset.StandardCharsets.UTF_8.name());
    
  • For JAR build, I just want to do it like this (if doing it without @Autowired):
    MyPrintStream myPrintStream = System.out;
    

If I have to do these on context/servlet XML for @Autowired, how can I initialize the object differently?

Note: Not sure if I am thinking this in the right way. Please correct me if I am wrong. Other opinions are also welcome.

0 Answers
Related