2026/6/28 17:50:27
网站建设
项目流程
博客网站模板有哪些,昆明网络推广昆明网站建设昆明昆明,网站建设asp文件怎么展现,dw做网站菜单栏一、IOC创建对象的4个核心注解
Controller - 用于标注控制器层组件#xff08;Controller层#xff09;Service - 用于标注业务逻辑层组件#xff08;Service层#xff09;Repository - 用于标注数据访问层组件#xff08;DAO层#xff09;Component - 用于标注非三层架构…一、IOC创建对象的4个核心注解Controller- 用于标注控制器层组件Controller层Service- 用于标注业务逻辑层组件Service层Repository- 用于标注数据访问层组件DAO层Component- 用于标注非三层架构的其他地方通用组件原理这些注解本质都是Component的衍生注解用于声明Bean并交由Spring容器管理二、Scope注解 - 控制对象作用域Scope(singleton)// 单例模式默认Scope(prototype)// 多例模式作用控制Bean是单例还是多例解决对象线程安全问题三、XML配置 - 注解扫描生效?xml version1.0 encodingUTF-8?beansxmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans https://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-scanbase-packagecom.luo//beans关键点component-scan标签开启注解驱动本质是BeanFactoryPostProcessor在操作四、DI依赖注入注解注解注入类型默认规则使用场景Value基本类型直接赋值字符串、数字等基本类型注入Autowired引用类型按类型注入byType同一类型Bean唯一时使用Resource引用类型按名字注入byName需要明确指定Bean名称时Qualifier配合Autowired按名字注入同一接口多个实现类时精确定位优势相比XML配置注解方式无需编写set方法开发更高效五、完整示例代码Service(userService)// 指定id为userService默认是首字母小写的类名Scope(singleton)publicclassUserServiceImplimplementsUserService{// 基本类型注入Value(19)privateintage;// 引用类型自动注入默认按类型AutowiredprivateUserDaouserDao;// 如果存在多个UserDao实现类可配合Qualifier使用// Autowired// Qualifier(userDaoImpl)// private UserDao userDao;OverridepublicvoidfindUserById(){userDao.findUserById();System.out.println(UserService!!!!);}}六、快速记忆口诀IOC四兄弟Controller、Service、Repository、ComponentScope控单例singleton默认prototype多例DI四剑客Value基本型Autowired类型Resource名字Qualifier配合XML扫注解component-scan包路径修改BeanIDComponent(“自定义名称”)七、原理补充理解性记忆所有注解生效的前提是Spring容器启动时通过context:component-scan扫描包路径将带有注解的类注册为BeanDefinition再由BeanFactory实例化并管理其生命周期