使用java的方式配置Spring(完全摒棄掉xml配置文件)

這種純java的配置,不會出現xml的配置方式,在SpringBoot中隨處可見

1、pojo類

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("甜甜")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

2、寫一個註解類

TtConfig類

//這個也會被Spring容器託管,註冊到容器中,因爲本來就是一個@Component
//@Configuration代表這是一個配置類,就像beans.xml一樣
@Configuration
@ComponentScan("com.tt.pojo")
@Import(TtConfig.class )
public class TtConfig {
    //註冊一個bean,就相當於我們之前寫的一個bean標籤
    //這個方法的名字,就相當於bean標籤中的id屬性
    //這個方法的返回值,就相當於bean標籤中的class屬性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的對象
    }
}

3、測試類

import com.tt.pojo.TtConfig;
import com.tt.pojo.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(TtConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章