2

I am beginner to spring. I have gone through some online tutorials and written a simple program, but I couldn't understand the worth. When we use spring.xml file and we create object with getBean method. But, in case of annotations I am creating the object using new, which I think is not right. Please see below the code and let me know if the procedure i have followed is problematic or not.

Hello.java:

package bean;

import org.springframework.stereotype.Component;

@Component
public class Hello {

    String gender;

    public void print(){
        System.out.println("Hello world "+gender);
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

AppConfig.java:

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import bean.Hello;

@Configuration
public class AppConfig {

    @Bean(name="h")
    public Hello getHello(){
        Hello h= new Hello();
        h.setGender("male");
        return h;
    }

}

Driver.java:

package client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import bean.Hello;
import config.AppConfig;

public class Driver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);

        Hello h=ct.getBean("h",Hello.class);

        h.print();

    }

}

As you can see in AppConfig.java, I am creating the object of my class using

Hello h= new Hello();

This looks problematic. If i have to create object by myself, then why do we need spring. Please suggest what I am doing wrong here.

5
  • The Spring object could be configured from a xml file. Very useful if you want to change values e.g. for a DB Connection or some other configuration Object Commented Oct 15, 2018 at 3:00
  • I want to use annotations not spring.xml file. Commented Oct 15, 2018 at 3:05
  • Hello h=ct.getBean("h",Hello.class); - what is wrong with this? Also search for bean injection Commented Oct 15, 2018 at 4:06
  • see the code in AppConfig class. Commented Oct 15, 2018 at 4:27
  • You should not create the class using new - see autowired or use the same method as per your main Commented Oct 15, 2018 at 4:29

5 Answers 5

1

Edit when you use @Component("h") , you are creating a bean with name h with certain properties defined in Hello class. So you don't need Appconfig class. And also you should not try to change beans properties (like setGender) elsewhere except in Hello class. So when should i use config class? When you dont mark Hello class as bean(i.e dont use component annotation). You create a Hello class object, set certain properties and mark it as a bean(using @bean).

No you don't have to create object by yourself. Mark Hello class as @Component("h") and you can get the bean directly using Hello h=ct.getBean("h",Hello.class); .

You can also use Autowired annotation to get your bean anywhere and do whatever you want to.

Sign up to request clarification or add additional context in comments.

3 Comments

then what should I write in AppConfig class. Current content is:@Configuration public class AppConfig { @Bean(name="h") public Hello getHello(){ Hello h= new Hello(); h.setGender("male"); return h; } }
In AppConfig class you can get your bean named h and add properties. You need to do the folowings @Autowired @Qualifier("h") private Hello hello; // get the bean hello.setGender("male"); // set properties
now I am getting null pointer exception on hello.setGender("male"); Can you please let me know what should be the contents of AppConfig class
1

Thera are 2 ways to be able to create a bean inside Spring Context

  1. Using @Component annotation (delegate creation Spring Framework )

@Component: annotation above a class indicates that this class is a component and should be automatically detected and instantiated. Thus a Spring component bean will look like :

@Component
public class User {
  private String name;

  private String address;

  public String getName() {
return name;
  }

  public void setName(String name) {
this.name = name;
  }

  public String getAddress() {
return address;
  }

  public void setAddress(String address) {
this.address = address;
  }
}

Scan your beans with component scan:

Xml old school Spring configuration:

  <context:component-scan base-package=”com.yourpackage” />

Component scan (If you use Spring boot it will be included inside @SpringBootAppilcation)

@ComponentScan(basePackageClasses = Yourclass.class)
  1. Using @Configuration annotation: (your actual choose)

Using @Configuration class with a method annotated with @bean. You should provide here how to create new object setting values (your getHello method):

 @Bean(name="h")
public Hello getHello(){
    Hello h= new Hello();
    h.setGender("male");
    return h;
}

Comments

0

You don't require to create bean explicitly in AppConfig.java class as you already have @Component annotation on Hello.java class. It will automatically create bean.

You can directly access the bean with your code in main but you need to specify name of bean in @Component as "h".

 ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);

        Hello h=ct.getBean("h",Hello.class);

        h.print();

2 Comments

then what should be the content of AppConfig class
There will be no content in AppConfig class. You can specify @ComponentScan there so that it scan and works on packages specified. And if you have any other configurations then you can specify them in AppConfig class.
0

You just need to use Autowired and have a getter

@Autowired
private Hello hello;

public Hello getHello () {return hello;}

Comments

0

Answering this question as there is no accepted answer. So, what you have done is one way of asking SpringContainer to create bean and that can be used in other places.

Basically, we can ask spring to create object for us using three types.

  1. XML-based Configuration,
  2. Annotation-based Configuration,
  3. Java-basedConfiguration.

You have used Java-based configuration. Its not like we should not use "new" keyword to create object when using spring framework. It is kind of useful at some scenarios like creating object of DataSource(providing database details).

So, if you want spring to create object for you along with object properties, we can make use of @component and @value annotation. Refer code below,

package com.vj.spring.springanno;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Hello {

    @Value("dummy value")
    String gender;

    
    public void print(){
        System.out.println("Hello world "+gender);
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

Your Appconfig class should look like this(read comments as well),

package com.vj.spring.springanno;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration // makes this class similar to spring.xml(old school way)
@ComponentScan("com.vj.spring") // replacement of <context:component-scan base-package=”com.yourpackage” /> in spring.xml
public class AppConfig {


    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Hello hello = context.getBean(Hello.class); // or context.getBean("hello",Hello.class);
        hello.print();

    }
}

By default, if use @component annotation, it creates reference name like "hello" (camelCase of Class name). If you would want so specify reference name, you could do like @component("h").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.