当前位置: 移动技术网 > IT编程>开发语言>Java > Spring 使用JavaConfig实现配置的方法步骤

Spring 使用JavaConfig实现配置的方法步骤

2020年03月09日  | 移动技术网IT编程  | 我要评论

不使用spring的xml配置,全权交给java来做!

javaconfig是spring的一个子项目,在spring4之后,它称为了spring的核心功能!

实体类:

package com.lrx.poji;

import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
//说明这个类被spring注册到了容器中
@component
public class user {
 @value("lixin")
 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.lrx.config;

import com.lrx.poji.user;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.componentscan;
import org.springframework.context.annotation.configuration;

//这个也会被spring容器托管,因为它本来就是一个@component
// @configuration代表一个类,就和我们之前的applicationcontext.xml是一样的
@configuration
@componentscan("com.lrx.poji")
public class liconfig {
  //注册一个bean,就相当于xml写的一个bean标签
  //这个方法的名字就相当于bean标签中的id属性
  //方法的返回值相当于bean标签中的class属性
  @bean
  public user getuser(){
    return new user();  //就是要注入到bean的对象
  }
}

测试类:

import com.lrx.config.liconfig;
import com.lrx.poji.user;
import org.springframework.context.applicationcontext;
import org.springframework.context.annotation.annotationconfigapplicationcontext;

public class mytest {
  public static void main(string[] args) {
    //如果完全使用了配置类方式去做,我们就只能通过annotationconfig上下文来获取容器
    // 然后通过配置类的class对象来加载!
    applicationcontext context=new annotationconfigapplicationcontext(liconfig.class);
    user getuser= (user) context.getbean("user");
    system.out.println(getuser.getname());
  }
}
 

这种纯java的配置方式在spring boot中随处可见!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网