小言_互联网的博客

Spring 通过注解来存储和读取对象

477人阅读  评论(0)

目录

1. 创建Spring 项目

1.1 创建⼀个 Maven 项⽬

 1.2 添加 Spring 框架支持

 1.3 添加启动类

2. 存储 Bean 对象

2.1 创建Bean 

2.2 配置 spring-config.xml

3. 获取并使用 Bean 对象

3.1 创建Sprign 上下文

 3.2  获取指定的 Bean 对象

 3.3 使用Bean

4.总结

更简单的获取和存储对象

5.配置扫描路径

6.添加注解存储 bean对象

6.1 @Controller(控制器存储) 

 6.2 @Service (服务器存储)

6.3 @Repository (仓库存储)

6.4 @Component (组件存储)

6.5 @Configuration(配置存储)

 6.6 为什么需要五大注解

6.7 方法注解 @Bean

6.7.1 方法注解配合类注解使用

6.7.2 重命名Bean

8.获取 Bean 对象

8.1 属性注入

 8.2 构造方法注入

8.3 Setter 注入

8.4 三种注⼊优缺点分析

8.5 @Resource:另一种注入关键字


1. 创建Spring 项目

1) 创建⼀个普通 Maven 项⽬。

2.)添加 Spring 框架⽀持(spring-context、spring-beans)。

3) 添加启动类。

1.1 创建⼀个 Maven 项⽬

 1.2 添加 Spring 框架支持

在项⽬的 pom.xml 中添加 Spring 框架的⽀持,xml 配置如下:


  
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework </groupId>
  4. <artifactId>spring-context </artifactId>
  5. <version>5.2.3.RELEASE </version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework </groupId>
  9. <artifactId>spring-beans </artifactId>
  10. <version>5.2.3.RELEASE </version>
  11. </dependency>
  12. </dependencies>

配置国内源

将下面两个框都要勾选上

 

 settings.xml 文件配置代码:


  
  1. <mirrors>
  2. <mirror>
  3. <id>alimaven </id>
  4. <name>aliyun maven </name>
  5. <url>http://maven.aliyun.com/nexus/content/groups/public/ </url>
  6. <mirrorOf>central </mirrorOf>
  7. </mirror>

修改位置如下

 配置好之后,如果想下一次的项目也使用该国内源,则需下面的配置

 

 1.3 添加启动类

最后在创建好的项⽬ java ⽂件夹下创建⼀个启动类,包含 main ⽅法即可

2. 存储 Bean 对象

存储 Bean 分为以下 3步:

1)存储 Bean 之前,先得有 Bean 才⾏,因此先要创建⼀个 Bean。

2) 配置⽂件 spring-config.xml

3)将创建的 Bean 注册到 Spring 容器中。

2.1 创建Bean 

Bean 就是 Java 语⾔中的⼀个普通对象,实现代码如下:


  
  1. public class User {
  2. public static void say (String name){
  3. System.out.println( "hello " + name);
  4. }
  5. }

2.2 配置 spring-config.xml

在文件中添加以下代码


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. </beans>

再将 User 对象注册到spring-config.xml 中就可以,具体操作是在 <beans> 中添加如下配置:

3. 获取并使用 Bean 对象

获取并使⽤ Bean 对象,分为以下 3 步:

1. 得到 Spring 上下⽂对象,因为对象都交给 Spring 管理了,所以获取对象要从 Spring 中获取,那么就得先得到 Spring 的上下⽂。

2. 通过 Spring 上下⽂,获取某⼀个指定的 Bean 对象。

3. 使⽤ Bean 对象。

3.1 创建Sprign 上下文

Spring 上下⽂对象可使⽤ ApplicationContext,代码如下


  
  1. public static void main (String[] args) {
  2. ApplicationContext context =
  3. new ClassPathXmlApplicationContext( "spring-config.xml");
  4. }

除了 ApplicationContext 之外,我们还可以使⽤ BeanFactory 来作为 Spring 的上下⽂,如下代码所示


  
  1. // 1.得到 bean 工厂
  2. BeanFactory factory = new XmlBeanFactory(
  3. new ClassPathResource( "spring-config.xml"));
  4. // 2.获取 bean
  5. User user = (User) factory.getBean( "user");
  6. // 3.使用 bean
  7. user.say( "黄小小");

ApplicationContext 和 BeanFactory 效果是⼀样的,ApplicationContext 属于 BeanFactory 的⼦类, 它们的区别如下

1)继承关系和功能⽅⾯来说:Spring 容器有两个顶级的接⼝:BeanFactory 和ApplicationContext。

其中 BeanFactory 提供了基础的访问容器的能⼒,⽽ ApplicationContext 属于 BeanFactory 的⼦类,它除了继承了 BeanFactory 的所有功能之外,它还拥有独特的特性,还添加了对国际化⽀持、资源访问⽀持、以及事件传播等⽅⾯的⽀持。

2)从性能⽅⾯来说:ApplicationContext 是⼀次性加载并初始化所有的 Bean 对象,⽽ BeanFactory是需要那个才去加载那个,因此更加轻量。

 3.2  获取指定的 Bean 对象


  
  1. //2.根据上下文对象提供的方法获取到 bean
  2. //User user = (User) context.getBean("user");//与spring-config.xml 中的id 一致
  3. //User user = context.getBean(User.class);//不需要强转,但不建议使用
  4. User user = context.getBean( "user",User.class); //精准并不需要强转,推荐使用

 3.3 使用Bean


  
  1. //3.使用
  2. user.say( "黄小小");

总代码:


  
  1. public class App {
  2. public static void main (String[] args) {
  3. //1.得到 spring 上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.根据上下文对象提供的方法获取到 bean
  7. //User user = (User) context.getBean("user");//与spring-config.xml 中的id 一致
  8. //User user = context.getBean(User.class);//不需要强转,但不建议使用
  9. User user = context.getBean( "user",User.class); //精准并不需要强转,推荐使用
  10. //3.使用
  11. user.say( "黄小小");
  12. }
  13. }

4.总结

更简单的获取和存储对象

5.配置扫描路径

想要将对象成功的存储到 Spring 中,我们需要配置⼀下存储对象的扫描包路径,只有被配置的包下的所有类,添加了注解才能被正确的识别并保存到 Spring 中。
在 spring-config.xml 添加如下配置:

    
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:content= "http://www.springframework.org/schema/context"
  5. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <content:component-scan base-package="com.beans"> </content:component-scan>
  7. </beans>

6.添加注解存储 bean对象

想要将对象存储在 Spring 中,有两种注解类型可以实现:
1)  类注解:@Controller、@Service、@Repository、@Component、@Configuration。
2)  ⽅法注解:@Bean

6.1 @Controller(控制器存储) 

使⽤ @Controller 存储 bean 的代码如下所示:
在要扫描的根路径(com.beans)下创建一个 UserController 类

   
  1. import org.springframework.stereotype.Controller;
  2. @Controller //将对象存储到Spring中
  3. public class UserController {
  4. public void sayHi () {
  5. System.out.println( "hello controller");
  6. }
  7. }
在main 方法中用读取对象的⽅式来读取上⾯的 UserController 对象,如下代码所示

    
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.得到bean
  7. UserController controller = context.getBean( "userController",UserController.class);
  8. //3.使用 bean
  9. controller.sayHi();
  10. }
  11. }

代码注入解释:

获取结果

 6.2 @Service (服务器存储)

使⽤ @Service 存储 bean 的代码如下所示:
在要扫描的根路径(com.beans)下创建一个 UserService类

     
  1. import org.springframework.stereotype.Service;
  2. @Service
  3. public class UserService {
  4. public void sayHi () {
  5. System.out.println( "hello service");
  6. }
  7. }

在main 方法中用读取对象的⽅式来读取上⾯的 UserService 对象,如下代码所示


     
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.得到bean
  7. UserService service = context.getBean( "userService",UserService.class);
  8. //3.使用 bean
  9. service.sayHi();
  10. }
  11. }

6.3 @Repository (仓库存储)

使⽤ @Repository 存储 bean 的代码如下所示:
在要扫描的根路径(com.beans)下创建一个 UserRepository 类

      
  1. import org.springframework.stereotype.Repository;
  2. @Repository
  3. public class UserRepository {
  4. public void sayHi () {
  5. System.out.println( "hello repository");
  6. }
  7. }

在main 方法中用读取对象的⽅式来读取上⾯的 UserController 对象,如下代码所示


      
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.得到bean
  7. UserRepository repository = context.getBean( "userRepository",UserRepository.class);
  8. //3.使用 bean
  9. repository.sayHi();
  10. }
  11. }

6.4 @Component (组件存储)

使用 @Component 存储 bean 的代码如下所示:
在要扫描的根路径(com.beans)下创建一个 UserComponent 类

       
  1. import org.springframework.stereotype.Component;
  2. @Component
  3. public class UserComponent {
  4. public void sayHi () {
  5. System.out.println( "hello component");
  6. }
  7. }

在main 方法中用读取对象的⽅式来读取上⾯的 UserComponent 对象,如下代码所示


       
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.得到bean
  7. UserComponent component = context.getBean( "userComponent",UserComponent.class);
  8. //3.使用 bean
  9. component.sayHi();
  10. }
  11. }

6.5 @Configuration(配置存储)

使用 @Configuration 存储 bean 的代码如下所示:

在要扫描的根路径(com.beans)下创建一个 UserConfig 类

       
  1. @Configuration
  2. public class UserConfig {
  3. public void sayHi () {
  4. System.out.println( "hello Configuration");
  5. }
  6. }

在main 方法中用读取对象的⽅式来读取上⾯的 UserConfig 对象,如下代码所示


       
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. //2.得到bean
  7. UserConfig config = context.getBean( "userConfig",UserConfig.class);
  8. //3.使用 bean
  9. config.sayHi();
  10. }
  11. }

 6.6 为什么需要五大注解

让代码可读性提高,能直观的判断当前类的用途

查看 @Controller / @Service / @Repository / @Configuration 等注解的源码发现,
这些注解⾥⾯都有⼀个注解 @Component,说明它们本身就是属于 @Component 的“⼦类。

6.7 方法注解 @Bean

6.7.1 方法注解配合类注解使用

1)创建一个 bean

在要扫描的根路径(com.beans)下创建一个  UserBeans 类

在 Spring 框架的设计中,⽅法注解 @Bean 要配合类注解才能将对象正常的存储到 Spring 容器中

       
  1. @Component
  2. public class UserBeans {
  3. @Bean
  4. public User user1 () {
  5. User user = new User();
  6. user.setId( 1);
  7. user.setName( "黄小小");
  8. return user;
  9. }
  10. }

然后创建一个User对象


       
  1. public class User {
  2. private int id;
  3. private String name;
  4. @Override
  5. public String toString () {
  6. return "User{" +
  7. "id=" + id +
  8. ", name='" + name + '\'' +
  9. '}';
  10. }
  11. public int getId () {
  12. return id;
  13. }
  14. public void setId (int id) {
  15. this.id = id;
  16. }
  17. public String getName () {
  18. return name;
  19. }
  20. public void setName (String name) {
  21. this.name = name;
  22. }
  23. }

在main 方法中用读取对象的⽅式来读取上⾯的 User 对象,如下代码所示


       
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. User user = context.getBean( "user1",User.class);
  7. System.out.println(user);
  8. }
  9. }

6.7.2 重命名Bean

当 User 类里面有多个对象时,可以通过设置 name 属性给 Bean 对象进⾏重命名操作,如下代码


  
  1. @Component
  2. public class UserBeans {
  3. @Bean(name = "in")
  4. public User user1 () {
  5. User user1 = new User();
  6. user1.setId( 1);
  7. user1.setName( "黄小小");
  8. return user1;
  9. }
  10. @Bean(name = "to")
  11. public User user2 () {
  12. User user2 = new User();
  13. user2.setId( 2);
  14. user2.setName( "杨通达");
  15. return user2;
  16. }
  17. }

 通过使用 Bean 里面的 name 就可以获取对象了


  
  1. public class App {
  2. public static void main (String[] args) {
  3. //1. 先得到上下文对象
  4. ApplicationContext context =
  5. new ClassPathXmlApplicationContext( "spring-config.xml");
  6. User user1 = context.getBean( "in",User.class);
  7. System.out.println(user1);
  8. User user2 = context.getBean( "to",User.class);
  9. System.out.println(user2);
  10. }
  11. }

8.获取 Bean 对象

获取 bean 对象也叫做对象装配,是把对象取出来放到某个类中,有时候也叫对象注⼊。
类似于把 B 中的对象取出来放到 A 类当中
对象装配(对象注⼊)的实现⽅法以下 3 种:
1. 属性注⼊
2. 构造⽅法注⼊
3. Setter 注⼊

8.1 属性注入

属性注⼊是使⽤ @Autowired 实现的。
下面将 UserService 类注⼊到 UserController2 类中。
UserService类

   
  1. @Service
  2. public class UserService {
  3. public void sayHi () {
  4. System.out.println( "hello service");
  5. }
  6. }

UserController2 类


   
  1. @Controller
  2. public class UserController2 {
  3. //对象注入方式1:属性注入
  4. @Autowired
  5. private UserService userService;
  6. public void sayHi () {
  7. userService.sayHi();
  8. }
  9. }

main方法


   
  1. public class App2 {
  2. public static void main (String[] args) {
  3. ApplicationContext context =
  4. new ClassPathXmlApplicationContext( "spring-config.xml");
  5. UserController2 userController2 =
  6. context.getBean(UserController2.class);
  7. userController2.sayHi();
  8. }
  9. }

获取结果

 整个获取的调用链过程:

 8.2 构造方法注入

其中UserService类和上面属性注入的一样。

构造⽅法注⼊是在类的构造⽅法中实现注⼊,如下代码所示

   
  1. @Controller
  2. public class UserController3 {
  3. private UserService userService;
  4. //构造方法注入(官方推荐)
  5. @Autowired
  6. public UserController3 (UserService userService) {
  7. this.userService = userService;
  8. }
  9. /*
  10. //当有多个构造方法时,上面的 @Autowired 不能省略
  11. public UserController3(UserService userService, int num) {
  12. this.userService = userService;
  13. }*/
  14. public void sayHi () {
  15. userService.sayHi();
  16. }
  17. }

8.3 Setter 注入

Setter 注⼊和属性的 Setter ⽅法实现类似,只不过在设置 set ⽅法的时候需要加上 @Autowired 注
解,如下代码所示: 

   
  1. @Controller
  2. public class UserController4 {
  3. private UserService userService;
  4. //Setter 注⼊
  5. @Autowired
  6. public void setUserService (UserService userService) {
  7. this.userService = userService;
  8. }
  9. public void sayHi () {
  10. userService.sayHi();
  11. }
  12. }

8.4 三种注⼊优缺点分析

1)属性注⼊的优点是简洁,使⽤⽅便;缺点是只能⽤于 IoC 容器,如果是⾮ IoC 容器不可⽤,并且只有在使⽤的时候才会出现 NPE(空指针异常)。
2)构造⽅法注⼊是 Spring 推荐的注⼊⽅式,它的缺点是如果有多个注⼊会显得⽐较臃肿,但出现这种情况你应该考虑⼀下当前类是否符合程序的单⼀职责的设计模式了,它的优点是通⽤性,在使⽤之前⼀定能把保证注⼊的类不为空。
3)Setter ⽅式是 Spring 前期版本推荐的注⼊⽅式,但通⽤性不如构造⽅法,所有 Spring 现版本已经推荐使⽤构造⽅法注⼊的⽅式来进⾏类注⼊了

8.5 @Resource:另一种注入关键字

在进⾏类注⼊时,除了可以使⽤ @Autowired 关键字之外,我们还可以使⽤ @Resource 进⾏注⼊,如下代码所示

   
  1. @Controller
  2. public class UserController4 {
  3. private UserService userService;
  4. //Setter 注⼊
  5. //@Autowired
  6. @Resource
  7. public void setUserService (UserService userService) {
  8. this.userService = userService;
  9. }
  10. public void sayHi () {
  11. userService.sayHi();
  12. }
  13. }
@Autowired 和 @Resource 的区别
1)出身不同:@Resource 来自于 JDK ,@Autowrired 是Spring 框架提供的
2)用法不同:@Autowired 支持属性注入、构造方法注入和Setter 注入,而 @Resource 不支持构造方法注入。
3)支持的参数不同:@Resource 支持更多的参数设置,比如 name 、type 设置,而@Autowired 只支持required 参数设置。

转载:https://blog.csdn.net/m0_60494863/article/details/125745723
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场