使用Java的方式来配置Spring

我们这节中,使用java配置的方式来配置Spring。不再使用XML文件

步骤1:新建一个java配置类:SpringConfig。=======================类似于XML文件

    在这个类中添加注解@Configuration让他变成配置类

步骤2:编写实体类,并使用@Bean使其变成一个bean===============类似于xml配置文件中的bean

    在java配置类中将这个类定义出来

import com.chen.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
    //等价于<bean id="getUser" class="com.chen.pojo.User"/>
    @Bean
    public User getUser(){
        return  new User();
    }
}
//一定要使用注解让他变成bean,才能在java配置代码中用到。
//说明这个类注册到了容器中
 @Component
public class User { private String zjhm; public String getZjhm() { return zjhm; } public void setZjhm(String zjhm) { this.zjhm = zjhm; } }

步骤3:测试

  

import com.chen.Config.SpringConfig;
import com.chen.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(SpringConfig.class);
        User user1 = (User)context.getBean("getUser");
        System.out.println(user1.getZjhm());
    }
}

4.其他关于java配置类注解

  

 

 

    这些java方式实现Spring配置,在SpringBoot中随处可见!!

posted @ 2021-11-21 22:48  qwedfrgh  阅读(100)  评论(0)    收藏  举报