【spring之获取bean的方式】

获取bean的方式:

1.在java文件中手动获取

   ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        Customer customer = (Customer) context.getBean("customer");
        System.out.println(customer);

2.在xml文件中对应的bean中添加 autowired=bytype/byname/constructor

//java文件
   ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        Customer customer = (Customer) context.getBean("customer1");
        customer.getMachine().play();
<!--xml-->
    <bean id="machine" class="com.my.pojo.Machine"/>
    <bean id="customer1" class="com.my.pojo.Customer" autowire="byType">
    </bean>

输出结果:
在这里插入图片描述

3.使用注解实现自动装配:

先看看使用注解配置什么

  1. 引入context依赖约束
  2. 引入注解支持
  3. 使用注解

context依赖约束:

<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
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

注解支持:

<context:annotation-config/>

使用注解实现自动注册:
虽然自动注册能方便bean在xml的手动注册,但是一些设置依赖xml能更方便维护(也可以用Componentscan注解实现):

在xml定义扫描路径,在这个路径下的所有包和类,系统都会识别其注解并自动注册

 <context:component-scan base-package="com.my" />

@Component:在类定义上表明可实现java类的自动注册
分层:dao层 @Repository
service层 @Service
controller层 @Controller
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

使用注解实现自动注入:
@Autowired :默认先按照类型找,多个同类型的则按照setXXX的xxx对应的beanid值来找
在这里插入图片描述
当容器中有多个machine类型的bean时,就需要配合qualifier来使用了,这样就是按照id来找了
在这里插入图片描述

@Resource :默认先按照beanid值找,没有则按照类型找
使用resource注解可能会报空指针的异常,需要在maven的pom.xml文件中导入对应包

<!-- Javax Annotation -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>jsr250-api</artifactId>
			<version>1.0</version>
		</dependency>

如果是annotaion模块不可见,那就是jdk版本问题了。。。需要降版本:在idea的菜单栏中选择file->settings->bulid,execution,deployment->java compiler->选择你的项目->选择jdk8及以下的版本

在这里插入图片描述
ps:
1.Resource注解在jdk8之后被取消了,autowired在开发中用得更多一点
2.以上两个注解不是通过构造器的方式注入的,按理来说是需要定义对应的set方法,但是经过本博主测试不设置也是可以通过的。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值