前言
本章节是复习Java,仅供参考
一、使用注解的方式注册bean到IOC容器中
applicationContext.xml
- 在使用注解的时候,可以在当前类的上面添加某些注解标识
- @Component:组件,理论上可以在任意的类上进行添加,在扫描的时候都会完成bean的注册
- @Controller:放置在控制层,用来接受用户的请求
- @Service:放置在业务逻辑层
- @Repository:放置在数据访问层
- 这四个注解写在类上面的时候都可以完成注册bean的功能,但是这些规定并不是Spring识别的标识
- 在Spring程序运行过程中,不会对这四个注解做任何区分,看起来是一样的,都会完成bean的注册功能
- 在实际开发过程中,最好能分清楚,提高代码的可读性
- 使用注解需要如下步骤:
1、添加上述四个注解中的任意一个
2、添加自动扫描注解的组件,此操作需要依赖context命名空间
3、添加自动扫描的标签context:component-scan - 在使用注解的时候,还需要告诉spring应该从哪个包开始扫描,一般在定义的时候都写上相同包的路径
需要导入context命名空间 - 在使用注解的时候没有定义id和class,那么如何根据id来进行识别
- 默认是把当前类的名称的首字母小写之后作为id,如果需要改变名称,那么需要在注解添加参数值value来完成修改名字的目的。
<?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
http://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"></context:component-scan>
<!-- <bean id="personController" class="com.controller.PersonController"></bean>-->
</beans>
public class myTest {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void test1(){
PersonController personController = context.getBean("personController", PersonController.class);
System.out.println(personController);
PersonService personService = context.getBean("personService", PersonService.class);
System.out.println(personService);
}
}
结果:
com.controller.PersonController@cc43f62
com.service.PersonService@5b218417
这里@Scope注解可以声明当前类是单例还是多例
@Controller
@Scope(value = "prototype")
public class PersonController {
}
public class myTest {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void test1(){
PersonController personController = context.getBean("personController", PersonController.class);
PersonController personController2 = context.getBean("personController", PersonController.class);
System.out.println(personController == personController2);
}
}
/**
结果:
com.controller.PersonController@402c4085
false
**/
二、定义扫描包时要包含的类和不要包含的类
- 在使用注解的时候,还需要告诉spring应该从哪个包开始扫描,一般在定义的时候都写上相同包的路径
后续继续更新