java自动注入注解_自动注入

1. 自动注入类的配置

1.1 基于.java文件的轻量配置

1.1.1 使用@Configuration注解

对于entity实体对象类,冠以@Configuration修饰。

@Configuration

public class User {

private String ID;

private String name;

public String getID() {

return ID;

}

public void setID(String ID) {

this.ID = ID;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "User{" +

"ID='" + ID + '\'' +

", name='" + name + '\'' +

'}';

}

public User(){

}

public User(String ID, String name) {

this.ID = ID;

this.name = name;

}

}

此时,可以直接调用@AutoWired注入对象。

@Autowired

private User user;

并将user对象输入,得到

1.1.2 使用@Import注解

取消修饰于User类的@Configuration方法,而对构造类使用@Import注解。

@RestController

@RequestMapping("/hello")

@Import(User.class)

public class HelloController {

@Autowired

private User user;

@RequestMapping("/hello")

public String hello(){

System.out.println(user);

return "hello world!";

}

}

虽然intellij IDEA开发环境静态检查会出错,但执行程序依然可以成功。

1.1.3 使用@Bean注解

这是对1.1.1的一种改进

创建配置类BeanConfigure

@Configuration

public class BeanConfigure {

@Bean

public User getUser(){

return new User(“123456”,“seekwind”);

}

}

此时依然可以成功注入。

也可以在BeanConfigure类中配置多个类。

@Configuration

public class BeanConfigure {

@Bean

public User getUser(){

return new User("123456","seekwind");

}

@Bean

public Administrator(){

return new Administrator("root","root");

}

}

通过这种方法注入的对象是单例的。可以在@Bean后追加注解实现多例。

@Bean

@Scope("prototype")

public User getUser(){

return new User("123456","seekwind");

}

终端输出两个对象不同

user == user1 ? false

1.2 基于xml文件的重量配置

在resource文件下创建spring.xml文件.

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

调用类使用@ImportResource("xml文件名")修饰.

@RestController

@RequestMapping("/hello")

@ImportResource("spring.xml")

public class HelloController {

@Autowired

private User user;

@RequestMapping("/hello")

public String hello(){

System.out.println(user);

return "hello world!";

}

}

依然可以注入成功。

2. 变量注入

2.1 值的注入

在application.properties文件中加入

name=seekwind

需要注入的变量用@Value注解修饰

@Value("${name}")

private String name;

下面表格罗列出普通变量、日期、数组集合、Map的注入方式

2.2 对象注入

增加pom.xml依赖

org.springframework.boot

spring-boot-configuration-processor

以User类的注入为例User.java:

@Component

@ConfigurationProperties(prefix = "user")

public class User{

private String ID;

private String name;

}application.properties:

user.ID=123456

user.name=seekwin

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值