Spring重注解配置JavaConfig

1.1 JavaConfig配置容器

JavaConfig 主要使用的注解
@Configuration:放在类的上面, 这个类相当于 xml 配置文件,可以在其中声明 bean
@Bean:放在方法的上面, 方法的返回值是对象类型, 这个对象注入到 spring ioc 容器

创建配置类 SpringConfig(相当于xml配置文件)

package com.ityg.config;

import com.ityg.pojo.Student;
import org.springframework.context.annotation.*;

/**
 * 1、@Configuration: 表示当前类相当于xml配置文件的作用
 *      在这个类中有很多方法,方法的返回值是对象。
 *      在方法上加@Bean注解,表示将方法的返回值对象放到容器里
 *         \@Bean = <bean></bean>
 */
@Configuration
public class SpringConfig {

    /**
     * 定义方法,方法的返回值是对象
     * \@Bean 将对象注入到容器中;位置:写在方法上
     * \@Bean 没有使用属性,默认对象名称是方法名
     */
    @Bean
    public Student createStudent(){
        Student s = new Student();
        s.setId(1002);
        s.setName("yg");
        s.setAge(22);
        return s;
    }

    /**
     * 定义方法,方法的返回值是对象
     * \@Bean 将对象注入到容器中;位置:写在方法上
     * \@Bean 没有使用属性,默认对象名称是方法名
     *      name、value 指定对象名称,相当于bean标签中的id
     */
    // @Bean(value = "valueStudent")
    @Bean(name = "valueStudent")
    public Student createStudent2(){
        Student s = new Student();
        s.setId(1003);
        s.setName("zt");
        s.setAge(21);
        return s;
    }
}

单元测试

//使用JavaConfig
@Test
public void test2() {
    //没有 xml 配置文件,使用 java 类代替 xml 配置文件的作用
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    Student s = (Student) ac.getBean("createStudent");
    System.out.println(s);
}

@Test
public void test3() {
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    Student s = (Student) ac.getBean("valueStudent");
    System.out.println(s);
}

1.2 @ImportResource

@ImportResource 是导入 xml 配置,等同于 xml 文件的 ‘<import resource=“classpath:”/>’

创建实体类

public class Cat {
    private Integer cardId;
    private String name;
    private Integer age;
    // get、set、toString
}

创建配置文件 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 id="myCat" class="com.ityg.pojo.Cat">
        <property name="cardId" value="1001"/>
        <property name="name" value="Tom 猫"/>
        <property name="age" value="3"/>
    </bean>
</beans>

创建配置类

import org.springframework.context.annotation.ImportResource;
/**
 * @ImportResource 是导入 xml 配置,等同于 xml 文件的 '<import resource="classpath:"/>'
 * 加上这个注解后就可以通过此配置类使用导入的xml文件中的配置
 */
@ImportResource(value = {"classpath:beans.xml","classpath:applicationContext.xml"})
public class SystemConfig {

}

单元测试

@Test
public void testSystemConfig(){
    ApplicationContext ac = new AnnotationConfigApplicationContext(SystemConfig.class);
    Student student = (Student) ac.getBean("myStudent");
    Cat cat = (Cat) ac.getBean("myCat");
    System.out.println("student=="+student.toString());
    System.out.println("cat=="+cat.toString());
}
/*
student==Student{id=1001, name='张三', age=20}
cat==Cat{cardId=1001, name='Tom 猫', age=3}
*/

1.3@ComponentScan

用于指定 spring 在初始化容器时要扫描的包。

相当于xml配置文件中的< context:component-scan base-package=“”/> 。

@Configuration
@ComponentScan("com.ityg")
public class SpringConfig {

    //相当于xml中的<bean id="myCount" class="com.pojo.Account">
    // @Bean("account")
    @Bean // 没有指定name属性值,默认为方法名
    public Account getAccount(){
        Account account = new Account();
        account.setId(1001);
        account.setName("Configuration");
        account.setBalance(1000.0D);
        return account;
    }
}

@ComponentScan加上这个注解后,就可以通过此配置类获取扫描到的bean

1.4 @PropertySource

用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定 properties 配置文件的位置。

@PropertyResource 是读取 properties 属性配置文件

@PropertySources 可以读取多个properties属性配置文件

@Value(“${keyName}”) :获取配置文件中的值

在 resources 目录下创建 userConfig.properties

username=root
password=123456

创建数据类,User

/**
 * \@Component:标记组件扫描(不添加Spring找不到;
 *	会报:NoSuchBeanDefinitionException: No bean named 'user' available)
 */
@Component("user")
public class User {

    //获取配置文件里对应键的值,并设置给属性
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;
}

修改SpringConfig 类配置文件

@PropertySource(value = "classpath:userConfig.properties")
@ComponentScan(value = "com.ityg.pojo")// 指定spring初始化容器要扫描的包,此配置会将com.ityg 包以及所有子包全部扫描
public class SpringConfig {}

单元测试

@Test
public void test5(){
    //测试使用@PropertySource注解读取配置文件
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    User user = (User) ac.getBean("user");
    System.out.println(user);
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值