Spring5学习(五)——使用Java注解的方式配置Spring


前言

本文在配置Spring时完全使用Java中的注解,不是按前文所述使用Spring中有的注解方法进行注解开发,也不是按前文所述依据配置.xml文件进行开发。但是会将Java中注解的功能与XML配置文件中一些语句的功能做对比,帮助理解学习。

实现方法

下面将以一个实例,说明如何使用Java的方式配置Spring。

1.创建一个测试实体类User

创建一个测试实体类User,添加属性username。
需要用到的注解:
@Component:该注解放在需管理的实体类前,说明该类被Spring管理,相当于创建了一个bean。与.xml文件的实体类注解一致。
@Value(“属性值”):该注解放在属性名前或者该属性set方法前,用于属性值的注入。与.xml文件的实体类注解一致。

@Component
public class User {
    private String username;

    public String getUsername() {
        return username;
    }

    @Value("属性值")
    public void setUsername(String username) {
        this.username = username;
    }

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

2. 创建配置类TestConfig

在该配置类中进行Spring配置。
其中注解的含义分别为:
@Configuration:写于类名前,说明该类是配置类。等同于.xml配置文件。
@ComponentScan(“包名”):扫描该包名下的文件,使得该包下的注解都生效。
@Import(TestConfig1.class):将其他文件的配置类导入该文件中。
@Bean:注解一个bean对象。等同于.xml中<bean></bean>

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.security.PublicKey;

@Configuration
@ComponentScan("包名")
@Import(TestConfig1.class)
public class TestConfig {

    @Bean // 等同于.xml中`<bean id="getUser" class="User"></bean>`
    public User getUser(){  // 方法名 = id, 返回值 = class
        return new User();  // return返回注入到bean中的对象
    }
}

3. 测试

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
    	// ApplicationContext为容器接口,容器在初始化时先去读取配置类,可传多个配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        User user = context.getBean("getUser", User.class);
        System.out.println(user.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值