Search code examples
javaspringpropertiesjavabeans

Java Beans from xml returns null pointer exception


Hi i got a little problem with my app. I'm trying to get bean data from xml.

beans.xml

        <bean id="s3Bean" class="com.example.demo.controller.S3Bean">
            <property name="s3Host" value="${s3.host}" />
            <property name="s3AccessKey" value="${s3.accessKey}"/>
            <property name="s3SecretKey" value="${s3.secretKey}"/>
            <property name="s3Bucket" value="${s3.bucket}"/>
        </bean>

S3Bean.java

@ImportResource("classpath:beans.xml")
public class S3Bean {

    private String s3Host;
    private String s3AccessKey;
    private String s3SecretKey;
    private String s3Bucket;

    public void setS3AccessKey(String s3AccessKey) {
        this.s3AccessKey = s3AccessKey;
    }

    public void setS3SecretKey(String s3SecretKey) {
        this.s3SecretKey = s3SecretKey;
    }

    public void setS3Bucket(String s3Bucket) {
        this.s3Bucket = s3Bucket;
    }

    public void sets3Host(String s3Host) {
        this.s3Host = s3Host;
    }
}

Class also have getters. In my controller im trying to get bean like that.

    public S3Bean getS3Bean() {return S3Bean;}
    public void setS3Bean(S3Bean s3Bean) {S3Bean = s3Bean;}
    private S3Bean S3Bean;
...
    S3Bean.getS3Host();

This get returns null pointer. When im geting bean from application context it prints fine.

            ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
            S3Bean bean = ctx.getBean(S3Bean.class);
            System.out.println(bean.toString());

Could you explain why the first way of getting property dosent working?

StackTrace

java.lang.NullPointerException: null
    at com.example.demo.controller.hello.sayHello(hello.java:27) ~[classes/:na]

27 line is S3Bean.getS3Host();


Solution

  • I found out what was the problem. I didnt declared S3Bean in beans.xml.

            <bean id="springBean.Impl" class="com.example.demo.controller.Impl">
                <property name="S3Bean" ref="springBean.S3Bean"/>
            </bean>