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

spring配置及容器使用详解

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

spring配置及容器使用详解

前言:
      Spring容器简单来说就是用来创建、配置、管理对象的,不再需要手动去实例化对象,直接拿来用就可以了。更多关于Spring容器介绍可查看官网。

1.引入spring依赖


    org.springframework
    spring-context
    5.3.14


2.配置Spring的三种方式及使用

XML配置方式
resources资源目录下创建spring.xml配置文件,内容如下:



        
		
		

通过spring.xml配置文件启动容器,并获取使用bean:

//启动容器
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");

//获取bean 两种方式都必须是spring配置文件中配置的bean才可获取

//方式一 通过spring配置文件重的id获取 返回Object对象需强转
//User suer = (User)ac.getBean("user")

//方式二 通过类.class获取 无需强转
User user = ac.getBean(User.class)

注解配置方式
创建一个类添加@Configuration注解,表示该类为配置类

@Configuration
public class MyConfig {

	//创建方法,在方法上添加@Bean注解,返回值类型为要加入容器管理的类
	//value属性值就相当于spring.xml中id的值
    @Bean(value = "user")
    public User createUser(){
        return new User();
    }
}
-------------------------------------------------------------------
@Configuration
@ComponentScan(basePackages = "com.test")
//可在类上添加@ComponentScan注解扫描指定包,包下类有
//@Repository,@Service,@Controller,@Component注解修饰的会被添加到容器
public class MyConfig {
}


//容器启动使用AnnotationConfigApplicationContext(MyConfig.class)
ApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);

//获取使用和XML一样
//User suer = (User)ac.getBean("user")
User user = ac.getBean(User.class)

XML+注解配置方式
XML+注解这种方式相对常用,同样是在resources资源目录下创建spring.xml配置文件



        
		
		
		
		
		
		
		

在需要实例化的类加上@Repository,@Service,@Controller,@Component注解其中一个即可

//启动容器
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");

//获取bean 两种方式都必须是spring配置文件中配置的bean才可获取

//方式一 通过spring配置文件重的id获取 返回Object对象需强转
//User suer = (User)ac.getBean("user")

//方式二 通过类.class获取 无需强转
User user = ac.getBean(User.class)

如果是web项目,可以在web.xml中配置初始化启动容器


    contextConfigLocation
    classpath:spring.xml



    org.springframework.web.context.ContextLoaderListener

可以用@Autowired、@Resource两个注解加在字段上自动注入

public class User2{

	@Resource
	public User user;
	
}

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

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

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