spring笔记2-注解配置纯java

java方式来配置Spring

完全不使用Spring的xml配置,全权交给java来做,javaConfig是Spring的子项目,在Spring4之后

//实体类
package com.kuang.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//这里注解的意思就是说明这个类被Spring接管了,这个类被注册到容器中
@Component
public class User {
    
    
    public String getName() {
    
    
        return name;
    }

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

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

    private String name;

}

配置类

package com.kuang.config;

import com.kuang.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;

//Configuration注解代表就是配置类,和我们写的beans.xml是一样的
//这个也会被spring容器托管,注册到容器中,因为她本身就是一个@Component组件
@Configuration
@ComponentScan("com.kuang.pojo")//这是一个扫描包,可以显示的扫描包中

//把多个配置类合并到一个
@Import(KuangConfig2.class)
public class kuangConfig {
    
    

    @Bean
    //@Bean表示注册一个bean,相当于之前写的bean标签,这个方法的名字就是bean中的id,返回值就是bean中的class属性
    public User getUser(){
    
    //测试类中getBean方法中,必须和这个方法保持一致
        return new User();
    }
}

多个配置类组合在一起用@Import()

测试类
import com.kuang.config.kuangConfig;
import com.kuang.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest7 {
    
    
    public static void main(String[] args) {
    
    
        //如果完全使用配置方法去做,我们就只能通过AnnotationConfigApplicationContext上下文来获取容器
        //通过配置类的class对象加载
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(kuangConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());

    }
}


猜你喜欢

转载自blog.csdn.net/weixin_45263852/article/details/113849615