想要将对象成功的存储到 Spring 中,我们需要配置一下存储对象的扫描包路径,只有被配置的包下的所有类,添加了注解才能被正确的识别并保存到 Spring 中。在spring-config.xml配置文件中插入代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描这个包的下所有类 -->
<context:component-scan base-package="com.spring.ioc" />
</beans>
注意:
如果我们创建的是SpringBoot项目,就不需要配置扫描路径。自带的启动类中的@SpringBootApplication注解就可以有扫描包路径的功能。我们就不需要创建spring-config.xml文件。
// 扫描包路径
@SpringBootApplication
public class IocApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(IocApplication.class, args);
}
}
想要将对象存储在 Spring 中,有两种注解类型可以实现:
@Component、@Controller、@Service、@Repository、@Configuration。@Bean。// 可以和其它注解替换使用
@Component
public class User {
User(){
System.out.println("一个普通类");
}
}
@Configuration
public class AppConfig {
@Bean
public String method() {
return "一个普通方法";
}
// 建议 @Configuration 和 @Bean 配套使用
// 相当于
}
DI(依赖注入)的体现一个类的构造依赖于另一个类的存在。
对象装配(对象注入)的实现方法以下 3 种:
@Autowired是一种注解,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。
// 前提是Hello类已经注册到Spring中了
@Component
public class Person {
// 1. 构造方法注入 [推荐]
@Autowired // 可以不写,建议写上(可读性)
public Person(Hello hello) {
System.out.println("Person的构造方法");
}
}
// 前提是Hello类已经注册到Spring中了
@Component
public class Person2 {
// 2. setter方法注入
@Autowired // 必须写
public void setHello(Hello hello) {
System.out.println("Person2的setHello()方法");
}
// 普通方法注入
@Bean // 利用@Bean的普通方法注入时,这里的Hello可以不用@Autowired注解
public Person createPerson(@Autowired Hello hello) {
System.out.println("createPerson(), hello = " + hello);
return new Person(hello);
}
}
// 前提是Hello类已经注册到Spring中了
@Component
public class Person3 {
// 3. 直接属性注入
@Autowired // 必须写
private Hello hello;
public void printHello() {
System.out.println(this.hello);
}
}
注入的关键字也不只有@Autowired关键字、还有关键字@Resource,和@Autowired用法是差不多的,但是也有区别:
// 获取对象
Hello hello = context.getBean("hello", Hello.class);
Person2 person = context.getBean("person2", Person2.class);
// 调用对象的方法
Person = person.createPerson(hello);
这就和之前的用法一样了。
总结:
提示:这里对文章进行总结:
以上就是今天的学习内容,本文是Spring的学习,学习了如何通过注解来管理Bean对象,认识了几种对象注册的注解和对象注入的注解。之后的学习内容将持续更新!!!