Spring(十二):使用JavaConfig实现配置

上一篇文章我们学习了使用注解开发,但还没有完全脱离xml的配置,现在我们来学习JavaConfig配置来代替xml的配置,实现完全注解开发。

下面我们用一个简单的例子来进行学习。

一、首先建立两个实体类

User:

package com.jms.pojo;

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

@Component
public class User {
    @Value("jms")
    private String name;
    private Address address;

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }
    @Autowired
    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                '}';
    }
}

Address:

package com.jms.pojo;

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

@Component
public class Address {
    @Override
    public String toString() {
        return "Address{" +
                "id=" + id +
                '}';
    }

    @Value("100")
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

两个简单的类,并且实现了值的注入和Bean的自动装配。

二、建立一个配置类

package com.jms.config;

import com.jms.pojo.Address;
import com.jms.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//@Configuration代表他是一个配置类,可以看作原来的xml文件,它本身还是一个@Component,所以它也被注册到Spring容器中,由Spring容器托管
@ComponentScan("com.jms.pojo")
@Configuration
public class JmsConfig {

    //这一个方法就相当于xml中的一个Bean标签,方法名对应id属性,返回值对应class属性
    @Bean
    public Address address() {
        return new Address();
    }

    @Bean
    public User getUser() {
        return new User();
    }
}

这个配置类的作用就是代替原来的xml配置文件,所以xml文件中有的功能这里基本上都可以配置。

上面只简单配置了最基础的Bean和ComponentScan扫描包。

三、测试

@Test
    public void test1() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JmsConfig.class);
        User user = applicationContext.getBean("getUser", User.class);
        System.out.println(user);
    }

Spring(十二):使用JavaConfig实现配置

注意点:

1.我们new的不再是ClassPathXmlApplicationContext对象,而是AnnotationConfigApplicationContext;

2.getBean方法中传入的是配置类里的方法名,因为方法名对应原来xml里的id。

(本文仅作个人学习记录用,如有纰漏敬请指正)

Original: https://www.cnblogs.com/jmsstudy/p/16731096.html
Author: 谁知道水烫不烫
Title: Spring(十二):使用JavaConfig实现配置

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/616418/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球