1.回顾以下我们用xml文件配置spring的方法,用标签定义了一个java类,或者说是java bean。用标签给java bean当中的属性赋值。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl" > <property name="name" value="AdminUser01"/> </bean> </beans>
@Component注解
用注解开发,我们用@Component这个属性来指代xml配置文件当中的<bean>标签。
如上个示例中,我们用<bean>标签,定义了一个id="bookDao"的bean,在Spring注解开发当中,我把@Component注解放在BookDaoImpl类上,通过这种方式告诉Spring,这是一个bean类。
@Component里面的值"bookDao"是给这个bean取个名字,默认可以不填写。
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.oxygen.dao.impl; import com.oxygen.dao.BookDao; import org.springframework.stereotype.Component; @Component ( "bookDao" ) public class BookDaoImpl implements BookDao { public void save() { System.out.println( "Book Dao Save..." ); } } |
我们用@Component注解标注了BookDaoImpl类,但Spring并不知道这个类,我们需要采用一种方式让Spring把我们标注@Component注解的类当中bean来管理。
这里,我们先用Spring的XML配置文件来明确告诉Spring去管理@Component标注的类。
1 | < context:component-scan base-package="com.oxygen.dao.impl"/>是告诉spring去某个包里扫描@Component注解坚持的类 |
1 2 3 4 5 6 7 8 | < beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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:component-scan base-package="com.oxygen.dao.impl"/> |
componen-scan就是让Spring去扫描知道包里面的所有java 类。
注意:
本文目前还是注解和xml配置混合在使用。
对Dao类使用了@Component注解
对于Spring容器的核心配置使用了xml配置
Spring给@Component注解提供了3个衍生注解,这三个注解与@Component注解的作用完全一样,只是意义更明确.
1 2 3 | @Controller :用于定义表现层bean @Service :用于定义业务层bean @Reponsitory :用于定义数据层bean |
在纯注解开发模式下,获取Spring容器的方法:AnnotationConfigApplicationContext
package com.oxygen; import com.oxygen.config.SpringConfig; import com.oxygen.dao.BookDao; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class); BookDao bookDao= (BookDao) ctx.getBean("bookDao"); bookDao.save(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!