栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring注解开发-01-纯注解开发入门

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring注解开发-01-纯注解开发入门

Spring3.0升级了纯注解开发,使用JAVA类替代配置文件,开启Spring快速开发赛道

一、@Configuration注解介绍

@Configuration:使用在类上,声明当前的类是一个配置类

package com.gg.config;

import org.springframework.context.annotation.Configuration;


@Configuration
public class SpringConfig {
}

作用:替代了applicationContext.xml文件

二、@ComponentScan注解介绍

@ComponentScan:使用在声明的配置类上,表明所需要扫描的包

package com.gg.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan("com.gg.dao")
public class SpringConfig {
}

作用:替代了applicationContext.xml文件中的 

 三、注解定义Bean

@Component:表明一个类会作为组件类。告知Spring要为这个类创建bean。

该注解是通过类路径扫描自动装配到容器中的

package com.gg.dao.impl;

import com.gg.dao.BookDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;


@Component
public class BookDaoImpl implements BookDao {
    @Override
    public void save() {
        System.out.println("book dao save");
    }
}

作用:等价于  

说明:@Component("bookDao")等价于xml配置文件中bean的id,

 Spring提供@Component注解的三个衍生注解

        @Controller:用于表现层bean定义

        @Service:用于业务层bean定义

        @Repository:用于数据层bean定义 

四、Bean对象的获取

使用:AnnotationConfigApplicationContext

继承树关系

 

package com.gg;

import com.gg.config.SpringConfig;
import com.gg.dao.BookDao;
import com.gg.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class App {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //  使用id获取
        BookDao bookDao = (BookDao) context.getBean("bookDao");
        System.out.println(bookDao);
        //  通过类获取
        BookService bookService = context.getBean(BookService.class);
        System.out.println(bookService);
    }
}

测试结果

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837611.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号