How to define a Spring bean using annotation instead of XML?

后端 未结 2 2023
旧巷少年郎
旧巷少年郎 2021-02-07 10:11

I have defined in a xml config file:


this works fine.

The b

2条回答
  •  有刺的猬
    2021-02-07 10:40

    this is a simple example that I have just made:

    Main.java

    package the.test;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.AbstractApplicationContext;
    
    public class Main {
    
    public static void main(String[] args) {
    
        AbstractApplicationContext aac = new AnnotationConfigApplicationContext(Person.class, Phones.class);
        Person person = aac.getBean(Person.class);
        System.out.println(person.getPhones().getPhoneOne());
        System.out.println(person.getPhones().getPhoneTwo());
        System.out.println(person.getSurname());
        System.out.println(person.getName());
        System.out.println(person.getAge());
        aac.close();
    
        }
    }
    


    Person.java

    package the.test;
    
    import javax.annotation.Resource;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    
    //you may use @ComponentScan("the.test") here and omit declaring 
    //"Phone.class" in the main method 
    
    public class Person {
    private int age;
    private String name;
    private String surname;
    
    private Phones phones;
    
    public int getAge() {
        return age;
    }
    @Value("33")
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    @Value("John")
    public void setName(String name) {
        this.name = name;
    }
    
    public String getSurname() {
        return surname;
    }
    
    @Value("Due")
    public void setSurname(String surname) {
        this.surname = surname;
    }
    
    public Phones getPhones() {
        return phones;
    }
    @Resource
    public void setPhones(Phones phones) {
        this.phones = phones;
    }
    }
    


    Phones.java

    package the.test;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class Phones {
    private String PhoneOne;
    private String PhoneTwo;
    
    public String getPhoneOne() {
        return PhoneOne;
    }
    
    @Value("987654321")
    public void setPhoneOne(String phoneOne) {
        PhoneOne = phoneOne;
    }
    
    public String getPhoneTwo() {
        return PhoneTwo;
    }
    
    @Value("123456")
    public void setPhoneTwo(String phoneTwo) {
        PhoneTwo = phoneTwo;
    }
    
    }
    

    this is completely based on Spring Annotation and is made on spring framework 4.2.5

    hope it helps.

提交回复
热议问题