栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring 纯javaConfig配置实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring 纯javaConfig配置实现

 

 

pom依赖


    4.0.0

    com.kgcSpring
    Spring0101
    pom
    1.0-SNAPSHOT
    
        spring-02-hellospring
        spring-03-ioc2
        spring-04-ioc3
        spring-05-ioc4
        spring-06-ioc5
        spring-07-ioc6
    

    
        
            org.springframework
            spring-webmvc
            5.3.18
        
        
            org.springframework
            spring-jdbc
            5.3.18
        
        
            junit
            junit
            4.13.1
        
    

实体类
package com.kuang.pojo;

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

public class User {
    @Value("狂神小迷弟")
    private String name;

    public String getName() {
        return name;
    }

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

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

 

 配置类
package com.kuang.config;

import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

//这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration 代表了一个配置类,就和我们之前的beans.xml一样
@Configuration
@ComponentScan("com.kuang.pojo")//扫描包
@Import(KuangConfig2.class)
public class KuangConfig {

    //注册bean, 就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id的属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User();
    }
}

 

 

package com.kuang.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class KuangConfig2 {

}
测试类
import com.kuang.config.KuangConfig;
import com.kuang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    @Test
    public void cc(){
        //如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器
        //通过配置类的class对象加载
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
        User getUser = context.getBean("user", User.class);
//        User getUser = context.getBean( User.class); 获取bean的方式  两种都行
        System.out.println(getUser.getName());
    }
}

用AnnotationConfigApplicationContext的原因 看下面源码

 

 

 

 

补充官方源码

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/839346.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号