Spring 中注解的基本使用

91 阅读1分钟

注解开发定义bean

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

    • @Controller: 用于表现层bean定义 (dao包,mapper包)
    • @service: 用于服务层bean定义 (service包)
    • @Repository: 用于数据层bean定义
  • Spring3.0 纯注解开发模式

不用再写applicationContext.xml文件,定义一个SpringConfig 类,通过注解代替配置文件,如下

package com.itheima.config;
​
import org.springframework.context.annotation.ComponentScan;   //基本配置   
import org.springframework.context.annotation.Configuration;  //  扫描文件配置@Configuration
@ComponentScan("com.itheima")
public class SpringConfig{
}
  • Configuration注解用于设定当前类为配置类

  • @ComponentScan 注解用于设定扫描路径,此注解只能添加一次,多个数据用数据格式添加

    @ComponentScan({"com.itheima.service","com.itheima.dao"})
    

通过注解实现Spring的简单初始化程序

  1. 配置文件 Spring-config
package com.zking.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
​
@Configuration
@ComponentScan("com.zking")
public class SpringConfig {
}
  1. 定义接口与类文件
// 接口
package com.zking.mapper;
​
public interface BookDao {
    public void save();
}
// 类文件
package com.zking.mapper.Impl;
​
import com.zking.mapper.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
​
​
@Repository
// @Scope 设置bean的作用范围 默认单例默认,可以手动设置多例模式prototype
@Scope("singleton")
public class BookDaoImpI implements BookDao {
    public void save() {
        System.out.println("book dao save。。。");
    }
    @PostConstruct
    public void init() {
        System.out.println("init ...");
    }
    @PreDestroy
    public void destroy() {
        System.out.println("destroy ... ");
    }
}
  1. 测试类
    @Test
    public void test1() {
//        这里记得要引入配置文件
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = ctx.getBean(BookDao.class);
        System.out.println(bookDao);
        ctx.close();
    }

运行结果:

基本配置运行结果.png