国王陛下万万岁

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

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();
}
}

 

posted on   国王陛下万万岁  阅读(542)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
 
点击右上角即可分享
微信分享提示