Springboot-pre 配置容器 使用xml和Configuration注解配置容器

63 阅读1分钟

java-新建class:vo.Student

  • resourses下新增 XML Configuration File-Spring Config
<!--  beans.xml:  声明bean对象-->
    <bean id="myStudent" class="vo.Student">
        <property name="name" value="刘思涵"/>
        <property name="age" value="20"/>
        <property name="sex" value="女"/>
    </bean>

test测试使用

/**
 * MyTest: 使用xml作为容器配置文件
 */
@Test
public void test01(){
    String config = "beans.xml";
    ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
    Student student = (Student)ctx.getBean("myStudent" );
    System.out.println("容器中的对象:"+student);
}
  • 在java中新建类 JavaConfig 使用Configuration和Bean注解

/**
 * Configuration:表示当前类是作为配置文件使用的,配置容器
 * 位置:在类的上面
 * SpringConfig类相当于beans.xml
 */
@Configuration
public class SpringConfig {
    /**
     * 创建方法,方法的返回值是对象,在方法上面加入@Bean
     * 方法的返回值对象就注入到容器中
     * @Bean:把对象注入到spring容器中,作用相当于<bean>
     *     使用位置:方法上 不指定对象名称,默认方法名是ID
     */
    @Bean
    public Student createStudent(){
        Student s1 = new Student();
        s1.setName("张三");
        s1.setAge(20);
        s1.setSex("男");
        return s1;
    }

    /**
     * 指定对象在容器中的名称 指定<bean>的id属性
     * @Bean(name="wangwu")
     * @return
     */
    @Bean(name="wangwu")
    public Student makeStudent(){
        Student s2 = new Student();
        s2.setName("王五");
        s2.setAge(20);
        s2.setSex("男");
        return s2;
    }

}

test测试使用

/**
 * 使用JavaConfig
 */
@Test
public void test02(){
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    Student student = (Student) ctx.getBean("createStudent");
    System.out.println("使用JavaConfig创建的bean对象:"+student);
}