温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Spring中对JavaConfig进行配置

发布时间:2021-03-22 16:44:35 来源:亿速云 阅读:126 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关怎么在Spring中对JavaConfig进行配置,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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());
  }
}

以上就是怎么在Spring中对JavaConfig进行配置,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI