Loading

Spring笔记(六):使用JavaConfig实现配置

 

时间:2021/10/28

 

之前我们都是通过xml文件来实现spring的配置,这次我们看一下如何完全通过Java来实现spring的配置(不需要xml文件),具体步骤如下:

1.编写实体类

@Component:表示这个类已经由spring托管

@Value:依赖注入,通过注释给bean的属性赋值

 1 package bupt.machi.pojo;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.stereotype.Component;
 5 
 6 @Component
 7 public class User {
 8 
 9     @Value("machi")
10     private String name;
11 
12     public String getName() {
13         return name;
14     }
15 
16     public void setName(String name) {
17         this.name = name;
18     }
19 
20     @Override
21     public String toString() {
22         return "User{" +
23                 "name='" + name + '\'' +
24                 '}';
25     }
26 }

 

2.编写配置类

这是使用Java类来起到之前xml配置文件的作用,可以单独建一个config包来存放。

@Configuration:相当于声明该类为一个配置文件(表明该类起到了之前beans.xml的作用)

@ComponentScan:扫描包

@Bean:相当于之前在xml配置文件中声明一个bean,该方法的方法名为bean的id,该方法的返回值类型相当于bean的class

 1 package bupt.machi.config;
 2 
 3 import bupt.machi.pojo.User;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.ComponentScan;
 6 import org.springframework.context.annotation.Configuration;
 7 
 8 @Configuration  //相到于一个beans.xml文件
 9 @ComponentScan("bupt.machi.pojo")   //扫描包
10 public class MyConfig {
11 
12     //相当于一个bean,其中方法名为id,返回值类型为class
13     @Bean
14     public User getUser(){
15         return new User();
16     }
17 }

 

3.编写测试类

 1 import bupt.machi.config.MyConfig;
 2 import bupt.machi.pojo.User;
 3 import org.junit.jupiter.api.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 6 
 7 public class MyTest {
 8 
 9     @Test
10     public void testUser(){
11         ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
12 
13         User getUser = context.getBean("getUser", User.class);
14         System.out.println(getUser);
15 
16     }
17 }

 

posted @ 2021-10-28 09:39    阅读(199)  评论(0编辑  收藏  举报