When using Spring DI via "@Autowired" gives NPE and as per comments if I tried giving "@Component" to TestLogger but gives "Consider defining a bean of type 'java.lang.String' in your configuration."
Project LogTester
@SpringBootApplication
public class TestSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringBootApplication.class, args);
System.out.println("TestSpringBootApplication !! ");
}
}
public class TestLogger {
private static final String KEY_VALUE_DELIMITER = "=";
private static final String KEY_VALUE_PAIR_SEPARATOR = ", ";
private static final String DOUBLE_QUOTES = "\"";
private static final String ESCAPED_DOUBLE_QUOTES = "\\\\\"";
private static final String MESSAGE_FIELD_KEY = "message";
private static final String THROWABLE_CLASS_FIELD_KEY = "throwableClassName";
private static final String THROWABLE_MESSAGE_FIELD_KEY = "throwableMessage";
private static final String STACK_TRACE_FIELD_KEY = "stackTrace";
private static final String STACK_TRACE_ELEMENT_SEPARATOR = ",";
private final Map<String,Object> _fieldsMap = new LinkedHashMap<>();
public TestLogger withField(String key, Object value) {
_fieldsMap.put(key, value);
return this;
}
private TestLogger(String message) {
withField(MESSAGE_FIELD_KEY, message);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
boolean firstIteration = true;
for (Map.Entry<String, Object> field : _fieldsMap.entrySet()) {
String key = field.getKey();
String value;
value = Objects.toString(field.getValue(), StringUtils.EMPTY);
// escape all double quotes
value = StringUtils.replace(value, DOUBLE_QUOTES, ESCAPED_DOUBLE_QUOTES);
// surround the value in double quotes if it contains a space
if (value.contains(StringUtils.SPACE)) {
value = DOUBLE_QUOTES + value + DOUBLE_QUOTES;
}
if (firstIteration) {
firstIteration = false;
} else {
sb.append(KEY_VALUE_PAIR_SEPARATOR);
}
sb.append(key).append(KEY_VALUE_DELIMITER).append(value);
}
return sb.toString();
}
}
Project B is just one main class to invoke the method of Project A LogTester
@Component
public class MainClass {
@Autowi
red
private static TestLogger obj;
public static void main(String[] args) {
System.out.println("HI");
System.out.println(obj.withField("key", "89899"));
}
}
pom.xml
<dependency>
<groupId>com.test</groupId>
<artifactId>logTester</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
Output is below when Exception in thread "main" java.lang.NullPointerException at test.MainClass.main(MainClass.java:24)