获取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.使用注解实现自动装配:
先看看使用注解配置什么
- 引入context依赖约束
- 引入注解支持
- 使用注解
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方法,但是经过本博主测试不设置也是可以通过的。。。