IDEA下创建Spring项目
2024-08-31 09:48:57
1、新建项目
如果手动引入lib,需要引入spring的4个核心包:
- spring-core.RELEASE.jar
- spring-context.RELEASE.jar
- spring-beans.RELEASE.jar
- spring-expression.RELEASE.jar
嫌麻烦的可以直接引入spring所有的jar包(21个)。
还需引入第三方依赖:
- commons-logging.jar。
也可以选择Download,IDEA会自动下载引入:
- spring常用的15个jar包
- commons-logging.jar
- aopalliance.jar
2、在src下新建包com.chy.bean,包下新建接口Animal、实现类Dog
package com.chy.bean; public interface Animal {
public void shout();
}
package com.chy.bean; public class Dog {
public void shout() {
System.out.println("汪汪汪");
}
}
3、在spring-config.xml中配置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 name="dog" class="com.chy.bean.Dog" />
</beans>
如果创建项目时忘记勾选创建spring-config.xml:
4、新建测试类com.chy.test.Test
package com.chy.test; import com.chy.bean.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-config.xml"); // 通过xml中Bean的name来获取该Bean的一个实例,返回的是Object,需要强转
// Dog dog = (Dog) applicationContext.getBean("dog"); //也可以使用class类型的参数直接指定类型
Dog dog = applicationContext.getBean("dog", Dog.class); dog.shout();
}
}
传统的对象创建方式:Dog dog=new Dog();
spring则是由容器创建、管理对象(Bean的实例),要使用对象时,从容器中通过bean的name来获取一个实例。
使用spring的时候,尽量不要使用new,把对象的创建都交给spring容器。
最新文章
- 初始化char指针--赋值和strcpy() 本质区别【转】
- HTTP 无法注册 URL http://+:9999/CalculatorService/。进程不具有此命名空间的访问权限
- 第21条:理解Objective-C错误模型
- Hashtable映射数据库字段
- 《SDN核心技术剖析和实战指南》3.3读书笔记
- 运行于64操作系统上的C#客户端通过WCF访问Oracle数据库不兼容问题
- 2015年十大热门Android开源新项目
- 思考一个关于Lambda表达式做为linq条件的问题
- 搭建阿里云 centos mysql tomcat jdk
- Codeforces 439E Devu and Birthday Celebration 容斥
- python excle读
- 如何监控 Java 垃圾回收机制: jps、jstack、jmap、jhat、jstat
- gulp和webpack的区别
- # Writing your first Django app, part 2
- 8.1 服务器开发 API 函数封装,select 优化服务器和客户端
- HDUOJ------敌兵布阵
- India and China Origins---hdu5652(二分 + bfs)或者(并查集)
- 3110: [Zjoi2013]K大数查询
- 在学习HTML——form表单中的label标签时的一点小体会
- mongoDB 固定集合(capped collection)
热门文章
- MSSQL Server 及 MSSQL Express版本 自动备份
- Deploy a plain HTTP registry
- Multitenancy
- Failed to open .vcf.gz: could not load index
- 媲美GWAS Catalog,囊括45万人数据,778个表型,3千万个位点的公共数据库:GeneATLAS
- Maven name=archetypeCatalog value=internal
- Efficient and Accurate Arbitrary-Shaped Text Detection with Pixel Aggregation Network(利用像素聚合网络进行高效准确的任意形状文本检测)
- DevOps-ISC,CSS,Prometheus,Ansible ,Terraform,zabbix
- Java开发笔记(一百四十七)通过JDBC管理数据库
- Centos7下RabbitMQ的安装与配置