spring boot 注入
Spring Boot常用的三种自动注入方式
1.Autowired注解
@Autowired注解是Spring提供,只按照byType进行注入。@Autowired如果想要按照byName方式需要加@Qualifier,一般跟Autowired配合使用,需要指定一个bean的名称,通过bean名称就能找到需要装配的bean。
2.Resource注解
@Resource注解是Java标准库提供。默认采用byName方式进行注入,如果找不到则使用byType。可通过注解参数进行改变。比起Autowired好处在于跟Spring的耦合度没有那么高。
3.构造参数注入
通过构造函数将依赖项注入到类中。这种方式是推荐的,因为它使得依赖项成为不可变的,并且有助于进行单元测试。
@Service
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
4.Setter方式注入
@Service
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
注意:注入配置文件中的静态变量
- 类上写@component注解
- 在定义的变量中不注入
- 在生成的set方法中注入
@Component
class Account{
private static String name;
private static int age;
@Value("需要注入的值")
public void setName(String name){
Account.name = name;
}
@Value("12")
public void setAge(int age){
Account.age = age;
}
}
4.基于SpringBoot的策略模式多实现类注入(Map注入)
- 定义一个通用的策略接口。
public interface PaymentStrategy {
void pay(double amount);
}
- 每个策略有自己的实现类,并通过
@Component
进行标注。
假设我们有三种支付策略:支付宝、微信支付和信用卡支付。
@Component("aliPay")
public class AliPayStrategy implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Using AliPay to pay " + amount + ".");
}
}
@Component("wechatPay")
public class WeChatPayStrategy implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Using WeChatPay to pay " + amount + ".");
}
}
@Component("creditCardPay")
public class CreditCardPayStrategy implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Using Credit Card to pay " + amount + ".");
}
}
- 在使用时,通过
Map<String, Strategy>
注入,String
代表标识符,可以是Bean
名称或自定义的标识。
在业务服务类中,通过Map<String, PaymentStrategy>
注入所有的策略实现,并通过名称或自定义的标识符来动态选择合适的策略。
@Service
public class PaymentService {
// 自动注入所有实现了 PaymentStrategy 的 Bean,并以 Bean 名称作为 Map 的 Key
@Autowired
private Map<String, PaymentStrategy> paymentStrategyMap;
public void executePayment(String strategyKey, double amount) {
PaymentStrategy paymentStrategy = paymentStrategyMap.get(strategyKey);
if (paymentStrategy == null) {
throw new IllegalArgumentException("Invalid payment strategy: " + strategyKey);
}
paymentStrategy.pay(amount);
}
}
- 测试
通过不同的strategyKey
传递,可以动态选择使用哪一种支付策略。
@SpringBootApplication
public class StrategyPatternApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(StrategyPatternApplication.class, args);
PaymentService paymentService = context.getBean(PaymentService.class);
paymentService.executePayment("aliPay", 100.0); // 使用支付宝支付
paymentService.executePayment("wechatPay", 200.0); // 使用微信支付
paymentService.executePayment("creditCardPay", 300.0); // 使用信用卡支付
}
}
Spring boot的属性注入
1.使用 @Value 注解进行属性注入
1.1在 application.properties
文件中定义属性
app.name=MySpringApp
app.version=1.0.0
app.description=This is a sample Spring Boot application.
1.2在 Java 类中使用 @Value
注解
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppConfig {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
@Value("${app.description}")
private String appDescription;
public void printAppInfo() {
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
System.out.println("App Description: " + appDescription);
}
}
1.3测试类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private AppConfig appConfig;
@Override
public void run(String... args) throws Exception {
appConfig.printAppInfo();
}
}
2.使用 @ConfigurationProperties
注解进行属性注入
@ConfigurationProperties
注解用于将一组相关的属性注入到一个 Java
类中,它比 @Value
注解更灵活,尤其适用于注入大量属性。
2.1在 application.properties
文件中定义属性
app.name=MySpringApp
app.version=1.0.0
app.description=This is a sample Spring Boot application.
2.2 创建一个 Java
类来接收这些属性
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfigProperties {
private String name;
private String version;
private String description;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void printAppInfo() {
System.out.println("App Name: " + name);
System.out.println("App Version: " + version);
System.out.println("App Description: " + description);
}
}
2.3 测试类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private AppConfigProperties appConfigProperties;
@Override
public void run(String... args) throws Exception {
appConfigProperties.printAppInfo();
}
}
注意:
有时候你可能希望在配置文件中没有提供某个属性时使用默认值,这时可以在 @Value 中指定默认值。
@Value("${app.unknownProperty:defaultValue}")
private String unknownProperty;