Spring基础之搭建简单的项目
来源:互联网 发布:json如何使用 编辑:程序博客网 时间:2024/05/16 06:00
spring 是无侵入性的轻量级容器框架,用于配置bean,并维护bean之间关系.
spring 的Ioc/DI(控制反转/依赖注入)
Ioc(控制反转,以前是应用程序去创建并管理对象,现在将这个任务交给Spring容器,就好像以前的军区既要建立训练军队,战时又要指挥军队打仗,现在是军区(Spring)主建,战区(应用程序)主战)。Ioc是从宏观上讲控制的反转,而DI是指具体如何实现Ioc,就是使用依赖注入,来配置及管理对象的依赖关系。
spring 的AOP(面向切面编程)
是OOP的补充和延续,把程序分解为方面或关注点。
创建一个简单的Spring项目
- 引入spring的开发包(最小配置spring.jar 该包把常用的jar都包括, 还要 写日志包 common-logging.jar)
- 创建spring的一个核心文件 applicationContext.xml, [hibernate有核心 hibernate.cfg.xml struts核心文件 struts-config.xml], 该文件一般放在src目录下。
- 编写javabean
//用户public class UserService {private String name;private CatService catservice;public String getName() { return name;}public void setName(String name) { this.name = name;}public CatService getCatservice() { return catservice;}public void setCatservice(CatService catservice) { this.catservice = catservice;}public void sayHello(){ System.out.println("hello "+name); catservice.sayMiao();}}//猫public class CatService {private String name;public String getName() { return name;}public void setName(String name) { this.name = name;}public void sayMiao(){ System.out.println("miaomiao "+name);}}
4.配置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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><!-- 在容器文件中配置bean(dao/service/action/数据源/domain) --> <!-- bean元素的作用是,当我们的spring框架加载时,会自动创建一个bean,并放入内存管理起来 相当于UserService userservice = new UserService(); userservice.setName("wmj"); 这里体现了注入的概念 --> <bean id="userService" class="com.service.UserService"> <property name="name"> <value>wmj</value> </property> <property name="catservice" ref="catservice"/> </bean> <bean id="catservice" class="com.service.CatService"> <property name="name" value="丢爷"/> </bean> </beans>
5.调用
public class Test {public static void main(String[] args) { //得到spring的applicationContext对象 ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml"); UserService us = (UserService) ac.getBean("userService"); us.sayHello();}}
6.运行结果
hello wmjmiaomiao 丢爷
阅读全文
0 0
- Spring基础之搭建简单的项目
- spring boot之简单项目搭建
- Spring项目搭建【简单】
- 搭建一个基础的Spring Cloud项目
- 02搭建一个简单的spring项目
- spring cloud-学习之路(一):搭建一个简单的Springboot项目
- spring boot项目基础搭建
- 简单spring mvc项目搭建
- spring-boot项目简单搭建
- 简单Spring MVC项目搭建
- AngularJS入门之简单的项目搭建
- Spring Boot实战之Spring项目的搭建
- spring+springMVC+mybatis的框架项目基础环境搭建
- Spring最基础的项目搭建与配置
- 基于maven+dubbo+spring+zookeeper的简单项目搭建
- Spring Boot-RESTfull API简单项目的快速搭建
- Spring Boot-RESTful简单项目的快速搭建
- Spring boot 搭建一个简单的 Java EE 项目
- Java Reflection 反射教程 [转]
- queue list
- 三次握手的第三个ACK包丢了,会发生什么?
- TOMCAT虚拟目录配置
- AI, ML, DL的区别
- Spring基础之搭建简单的项目
- mysql列的数值型,字符型,日期型
- 进程间通信方式
- Mysql数据库主从+Amoeba读写分离
- VS-C++的一些实用快捷键(望大家一起来补充)
- codeforces 892A. Greed
- 多线程编程
- 深究标准IO的缓存
- 外挂与程序猿伦理