XML和JavaConfig

XML和JavaConfig

什么是JavaConfig

JavaConfig是Spring提供的使用java类来作为xml配置文件的替代,是配置spring容器的纯java方式,在这个java类中可以创建java对象,把对象放入spring容器中.
要使用两个注解:

  1. @Configuration : 放在一个类的上面,表示这个类是作为一个配置文件使用的
  2. @Bean : 声明对象的,把这个对象注入到容器中

原来的方式
我们先看一下之前的spring项目中,bean的注入是如何完成的
我们在spring的主配置文件中,通过xml文件的方式注入,下面是主配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--bean对象-->
    <bean id="myStudent" class="org.zjb.vo.Student">
        <property name="name" value="张三"></property>
        <property name="age" value="22"></property>
        <property name="sex" value=""></property>
    </bean>
</beans>

测试代码

    /**
     * 使用xml作为容器配置文件
     */
    @Test
    public void test01() {
        String config = "beans.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        Student student = (Student) ctx.getBean("myStudent");
        System.out.println(student);
    }

@Configuration

使用@Configuration注解
文件结构
在config包下创建SpringConfig类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zjb.vo.Student;

/**
 *  这个注解的作用是表示当前类是作为配置文件的,就是用来配置容器的
 *      位置 : 类的上面
 *
 *      SpringConfig这个类就相当于beans.xml
 */
@Configuration
public class SpringConfig {

    /**
     *  创建方法,方法的返回值是对象,在方法上加入@Bean
     *  方法的返回值就注入到了容器中
     *
     *  @Bean : 把对象注入到Spring容器中,相当于<bean></bean>
     *      位置 : 方法的上方
     *      说明 : 不指定名称,默认bean的id是方法名
     */
    @Bean
    public Student createStudent() {
        Student s = new Student();
        s.setName("张三");
        s.setSex("男");
        s.setAge(22);
        return s;
    }

    /**
     *  指定对象在容器中的名称,通过注解的bean属性
     */
    @Bean(name = "zhangsanStudent")
    public Student makeStudent() {
        Student s = new Student();
        s.setName("张三");
        s.setSex("男");
        s.setAge(22);
        return s;
    }
}

可以看见@Configuration这个注解的位置是在类的上面,表示这个类代表的是一个配置文件.
@Bean注解的位置是在方法上面,这个被Bean注解标注的方法,需要有bean对象作为返回值,如果不使用@Bean注解的name属性,则这个bean的id为方法名.
测试代码如下:

    /**
     * 使用JavaConfig作为容器配置文件
     */
    @Test
    public void test02() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student student = (Student) ctx.getBean("createStudent");
        System.out.println(student);
    }

    /**
     * 使用JavaConfig作为容器配置文件
     */
    @Test
    public void test03() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student student = (Student) ctx.getBean("zhangsanStudent");
        System.out.println(student);
    }

@ImportResoure

@ImportResoure作用导入其他的xml配置文件,等于在xml文件中的import标签
看例子 :
applicationContext.xml文件的内容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myCat" class="org.zjb.vo.Cat">
        <property name="name" value="Tom"></property>
        <property name="age" value="2"></property>
        <property name="cardId" value="uw00001"></property>
    </bean>
</beans>

需要在原先的SpringConfig类中引入这个xml的配置.
代码为 :

@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
public class SpringConfig {

}

测试代码如下 :

    @Test
    public void test04() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Cat cat = (Cat) ctx.getBean("myCat");
        System.out.println(cat);
    }

现在如果我们需要导入多个xml配置文件,其实@ImportResoure的value属性的值是一个数组
所以如下即可

// 导入多个xml文件
@ImportResource(value = {"classpath:applicationContext.xml", "classpath:applicationContext1.xml"})
public class SpringConfig {

}

@propertyResource

@PropertyResoure该注解读取property属性配置文件,使用属性配置文件可以实现外部化配置,在程序之外提供数据.
步骤 :

  1. 在resources目录下,创建properties文件,使用key=value的格式提供数据
  2. 在PropertyResource指定properties文件的位置
  3. 使用@Value(value = “$(key)”)

看一个例子:
我们通过注解注入的方式创建Tiger类型的bean对象.

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

@Component("tiger")
public class Tiger {

    @Value("${tiger.name}")
    private String name;
    @Value("${tiger.age}")
    private Integer age;

    @Override
    public String toString() {
        return "Tiger{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

config.properties配置文件如下

tiger.name=东北虎
tiger.age=3

SpringConfig类

import org.springframework.context.annotation.*;
import org.zjb.vo.Student;

@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
// 该注解指定属性配置文件的位置
@PropertySource(value = "classpath:config.properties")
// 该注解是组件扫描器,指定bean对象所在的包
@ComponentScan(basePackages = "org.zjb.vo")
public class SpringConfig {
}

测试代码

    @Test
    public void test05() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Tiger tiger = (Tiger) ctx.getBean("tiger");
        System.out.println(tiger);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值