Search code examples
javaxmlspringlegacy

How to fix main method not being executed in java, when no error is showing?


I have created a bean through XML for account. My main method should at the moment just print the constructor-args I've added to this bean. The program runs without errors, but main is not executing, so I have no output in the console.

It is a spring legacy project (simple maven), and has a H2 database which is currently empty as I haven't used it.

I have checked my main method with a print after each line, none are printing so I don't think it is hitting the method at all.

I've checked my beans.xml, and the design seems to have been created successfully. I've double checked my pom.xml to make sure I have the correct groupId. I've also right click on the mainApp file and gone to run as - run configurations, main and made sure it's including system files. In here it has main class marked as h2.console.

MainApp.java

package com.r00107892.bank;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.r00107892.bank.domain.Account;

public class MainApp {

    public static void main() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext ("beans.xml");
        Account account = (Account) context.getBean("account");
        System.out.println(account);
    }
}

beans.xml

<bean class="com.r00107892.bank.domain.AccountImplementation" id="account">
    <constructor-arg name = "accountNumber" value="1"></constructor-arg>
    <constructor-arg name = "balance" value="1000"></constructor-arg>
    <constructor-arg name = "overdraft" value="500"></constructor-arg>
</bean>'''

I expect to see the properties of the bean printed, instead my console just shows the cursor, like it's waiting for input.


Solution

  • Your main method's signature is wrong. It should be public static void main(String[] args)

    The constructor args tag in your xml configuration will pass the corresponding value to the constructor of the parent bean's class, which is AccountInformation in your code. It doesn't get passed to the main method, the main method's parameter is always of type String[].

    Your AccountInformation class needs a constructor like this:

    AccountInformation(int accountNumber, int balance, int overdraft)
    

    Note: the arguments don't have to be integers. They can be any compatible type. See this for more information:

    https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-ctor-arguments-resolution