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

Spring @configration(注解配置所需环境)

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

Spring @configration(注解配置所需环境)

1.@configration

  • 作用: @Configuration:表明当前的类是一个配置类,Spring中配置类有特殊的地位,一般有一个核心的配置类,用来构建Spring容器,也可以写普通配置类被其他的配置类加载
  •  @ComponentScan:指定Spring要扫描的包(当Spring构建容器时,将会扫描这个包以及它的子包,扫描所有的注解)
  •   基于这两个注解以及AnnotationConfigApplicationContext注解配置核心容器类,可以实现无XML的零配置

解决问题:

不需要每次都扫描

包。




    //配置好之后这行就用不到了

现在离不开配置文件,主要是因为其中有一句配置信息告诉spring在创 建bean容器时需要扫描的包,这个时候spring就会扫描指定的包以及 下面的子包中所有类上或者接口上的注解: 这里需要能够起到相同功能的类和注解就是@configration

1.(1)建立配置类

• 类名和包名都可以更改,不限制

(2)关键注解

• @Configuration 作用:指定当前类是一个配置类 • @ComponentScan 作用:用于指定spring在创建容器时要扫描的包 属性:value/basePackages:它们作用相同,都是用于指定创建容器时要扫描 的包 使用了此注解后,就相当于配置了XML中的 public static void main(String[] args) { // 1. 获取核心容器对象 //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); IUserService service = (IUserService) context.getBean("userService"); System.out.println(service); System.out.println(service.queryUser()); // 3.关闭容器(如果不记得关闭容器,最典型的问题就是数据库连接不能释放) //((ClassPathXmlApplicationContext) context).close(); ((AnnotationConfigApplicationContext) context).close(); }

自己写的扫描配置文件SpringConfig

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

@Configuration
@ComponentScan("com.iflytek.bookmanagesystem")
public class SpringConfig {

}

 

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

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

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