Spring 学习笔记(一)

来源:互联网 发布:servlet修改表单数据 编辑:程序博客网 时间:2024/05/18 02:38

Spring :Java开源轻量级框架,不需要使用到Spring的API,无依赖,注入性不强


Spring 关键知识点:

1、IOC / DI 反转控制/依赖注入  反转资源获取的方向 / 通过配置注入 


2、AOP 面向切面编程,将共同部分提取出来,通过配置文件进行管理



Eclipse 上有个Spring tool,装了几次没装成功。后面决定用Myeclipse 进行相关学习。


1.新建一个普通的Java项目

2.建好包和类

3.右击项目,选择Myeclipse -  Projects facets - install spring facet 


4.选择好版本,就算搭建了一个Spring项目了。


创建一个User类,

属性为:username ,password,

包含以下方法:getset方法。toString方法。无参构造函数,有参构造函数。


配置文件内容:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-4.1.xsd"><bean id = "test" class="com.harry.spring.learning.User"><property name="username" value="huanghong"></property><property name="password" value="harrysir"></property></bean></beans>
Main函数代码:

public static void main(String[] args) {ApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");User user = (User)ctx.getBean("test");System.out.println(user);}

在IOC容器中取出id为test的bean对象。

可以尝试只执行第一句,会发现在容器在创建的时候,会调用无参构造函数初始化对象。

传统的做法,得先创建User对象,然后set username 和password。

Spring将对象统一交给IOC容器来管理。

1 0
原创粉丝点击