9.使用JAVA的方式配置Spring

9.使用JAVA的方式配置Spring

我们现在要完全不使用Spring的XML配置了,全部交给java来做

JavaConfig是Spring的一个子项目,在Spring4之后它成为了核心功能

 

 

9.1.Component将实体类注入到容器中

//这个注解的意思就是,这个类被Spring接管了,将其注入到了容器中
@Component
public class User {
    @Value("小飞")//给name赋值
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

9.2.利用Configuration注解代替了之前的beans.xml

package com.itxiaofei.config;
import com.itxiaofei.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

//这个也会被Spring容器管理,注册到容器中去,因为他本身就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前的beans.xml一样
@Configuration
//扫描包的注解。=<context:component-scan base-package="com.itxiaofei.pojo"/>
@ComponentScan("com.itxiaofei.pojo")
//导入xiaofeiConfig2这个配置类
@Import(xiaofeiConfig2.class)
public class xiaofeiConfig {
    //注册一个bean,就相当于我们之前在beans.xml里写的一个bean
    //这个方法的名字就相当于bean标签中的id属性
    //这个方法的返回值就相当于,bean标签的class属性
    @Bean
    public User user(){
        return new User();//就是返回要注入到bean的对象
    }
    //等同于:
    // <beans>
    //    <bean id="user" class="com.itxiaofei.pojo.User"/>
    //</beans>

}

9.3.完全使用配置方法做的实体类(不用bean.xml)

import com.itxiaofei.config.xiaofeiConfig;
import com.itxiaofei.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {

        //如果完全使用了配置方式去做(也就是不用beans.xml)
        //我们就只能通过AnnotationConfig 上下文获取容器,通过配置类的class对象加载。

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(xiaofeiConfig.class);
        User getUser = context.getBean("user", User.class);
        System.out.println(getUser.getName());
    }
}
posted @ 2022-10-28 09:06  It小飞呀  阅读(25)  评论(0编辑  收藏  举报