使用JavaConfig实现配置

javaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能。

实体类

package com.xi.pojo;

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

@Controller
public class User { 
    private String name;

    public String getName() { 
        return name;
    }
    @Value("金角大王")
    public void setName(String name) { 
        this.name = name;
    }

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

配置文件

package com.xi.config;

import com.xi.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;

@Configuration
@ComponentScan("com.xi.pojo")
@Import(XiConfig2.class)//把其他的配置文件放到一起
public class XiConfig { 
    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){ 
        return new User();//返回要注入到bean的对象
    }
}

测试类

import com.xi.config.XiConfig;
import com.xi.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest { 
    public static void main(String[] args) { 
        ApplicationContext context = new AnnotationConfigApplicationContext(XiConfig.class);
        User getUser = context.getBean("getUser",User.class);
        System.out.println(getUser.getName());
    }
}

org.springframework.context.ApplicationContext 接口类定义容器的对外服务,通过这个接口,我们可以轻松的从IoC容器中的得到Bean对象。我们在启动Java程序的时候必须要先启动IoC容器。

Annotation类型的IoC容器对应的类是
org.springframework.context.annotation.AnnotationConfigApplicationContext

我们如果要启动IoC容器,可以运行下面的代码
ApplicationContext context = new AnnotationConfigApplicationContext(XiConfig.class);
这段代码的含义就是启动IoC容器,并且会自动加载XiConfig类下的bean。

AnnotationConfigApplicationContext 这个类的构造函数有两种

  • AnnotationConfigApplicationContext(String … basePackages) 根据包名实例化
  • AnnotationConfigApplicationContext(Class clazz) 根据自定义包扫描行为实例化

本文地址:https://blog.csdn.net/weixin_49563267/article/details/114265520