Spring基于java方式的配置

@configuration注解可以完全使用java的方式配置Spring

完全不使用xml配置,全权交由java来做

  • 创建实体类Student
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component
public class Student{
    
    
    private int id;
    private String name;
}
  • 创建配置类MyConfig

@Configuration
@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {
    
    
    @Bean
    public Student student(){
    
    
        return new Student(1,"xxxxxxxx");
    }
}

测试:

public class Test01 {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(MyConfig.class);
        Student student = applicationContext.getBean("student", Student.class);
        System.out.println(student);
    }

    @Test
    public void test2(){
    
    
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(MyConfig.class);
        Object student = applicationContext.getBean("student");
        System.out.println(student);
    }
}

おすすめ

転載: blog.csdn.net/m0_57184607/article/details/120693738