Spring 更简单的存储对象Bean

 Spring 中想要更简单的存储和读取对象的核心是使用注解

之前我们存储 Bean 时,需要在 spring.xml中添加一行bean 注册内容才行

但是现在只需要一个注解就可以替代之前要写一行配置的麻烦,但是首先还是要配置扫描路径,但是这里需要注意,包的位置要写清楚,否则也扫描不到,名称无所谓,也不用写的非常具体,我就用com.abc
在这里插入图片描述

<?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:content="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans htt
p://www.springframework.org/schema/beans/spring-beans.xsd http://www.spring
framework.org/schema/context https://www.springframework.org/schema/contex
t/spring-context.xsd">
 <content:component-scan base-package="com.abc"></content:compon
ent-scan>
</beans>

一,存储Bean(2种方法)

1.类注解

@Controller(控制器存储)、@Service(服务存储)、@Repository(仓库存储)、@Component(组件存储)、@Configuration(配置存储)

这5个的使用方法相同,就只举一个例子
使用@Controller 存储 bean 的代码如下所示:


@Controller // 将对象存储到 Spring 中
public class UserController {
 public void sayHi() {
 System.out.println("Hi!");
 }
}

先使用之前读取对象的方式来读取上面的 UserController 对象,如下代码所示:

public class Application {
 public static void main(String[] args) {
 // 1.得到 spring 上下⽂
 ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
 // 2.得到 bean
 UserController userController = context.getBean("userController",UserController.class);
 // 3.调⽤ bean ⽅法
 userController.sayHi();
 }
}

2.方法注解

@Bean
通常方法注解要配合类注解一起使用,才能将对象正常的存储到Spring容器中


@Component
public class Users {
 @Bean
 public User user1() {
 User user = new User();
 user.setId(1);
 user.setName("Java");
 return user;
    }
 }
 

二. Bean 命名规则

1.bean 使用的都是标准的大驼峰命名,而读取的时候首字母小写就可以获取到 bean 了
在这里插入图片描述

2.类名首字母和第二个字母都大写时,使用原类名读取
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值