Java框架之Spring IOC的注释应用

前言

本章节是复习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应该从哪个包开始扫描,一般在定义的时候都写上相同包的路径

后续继续更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

By丶小辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值