1.springIOC到底是什么?
重要的就是用来完成对对象的创建以及依赖注入的管理等。按照我们以前的编程方式,需要对象就直接new即可,然后为对象和构造方法及方法等赋值,需要对象的创建对象,需要方法则调用方法,然后再去设置参数,而spring为我们把这些事都省略了,简化了我们的操作,那么就都由spring来为我们管理,直接帮我们注入,所以这个就是所谓的依赖注入。
2.搭建环境
spring肯定不会无缘无故从天而降,肯定需要导入相关的jar包,而spring也需要我们的提示,才会按需注入,所以肯定需要相关的配置来告诉spring如何配置注入。
然后第一个属于工具包,不导入也会报错,剩下五个属于spring的核心jar包。如果以后还需要spring的其他功能则再导入其他jar包。
目录结构:
3.spring入门Helloworld
首先肯定需要导入相关jar包,上面以述
首先需要配置spring的配置文件
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="user" class="cn.spy.pojo.User"></bean>
</beans>
然后编写HelloWorld.java,有两种实现,一种是通过工厂方式创建对象,还有一种是直接创建对象。
public class HelloWorld {
@Test
public void testIOC1() throws Exception{
Resource resource =new ClassPathResource("cn/spy/first/applicationContext.xml");
@SuppressWarnings("deprecation")
BeanFactory factory =new XmlBeanFactory(resource);
User user =(User) factory.getBean("user");
System.out.println(user.getId()+" : "+user.getUsername());
}
@Test
public void testIOC2() throws Exception{
ApplicationContext context= new ClassPathXmlApplicationContext("cn/spy/first/applicationContext.xml");
System.out.println("-----容器创建完成-----");
User user =(User) context.getBean("user");
System.out.println(user.getId()+" : "+user.getUsername());
}
}
public class User {
private int id=1;
private String username="张三";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
分别测试两个方法,结果都为:
------------------------------------
细节:
<1>.创建对象分为单例和多例:需要在配置文件中直接scope属性来配置scope="singleton"为单例(就是默认值),在启动(容器初始化之前)就已经创建了bean,且整个应用只有一个。scope="prototype"是多例。它的创建则是在使用的时候才创建对象。
<2>.延迟创建:在配置文件中直接使用lazy-init属性来配置。lazy-init="false"就是不延迟创建对象,在系统启动的时候就创建对象,这个是默认值。 lazy-init="true"就是延迟初始化,在用到对象的时候才创建对象。(只对单例才会有效)。
<3>.创建对象后,方法的初始化和销毁:在配置文件中采用init-method属性进行配置,init-method="初始化执行方法"。这个方法在对象创建完之后执行。destroy-method="销毁执行方法",在容器对象执行destory();销毁方法的时候执行。
4.spring创建对象
(1)调用无参数构造器创建对象(默认方式)
配置相关的配置文件applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="shopping1" class="cn.spy.pojo.Shopping"></bean>
</beans>
pojo:
public class Shopping {
private String name;
private String price;
public Shopping() {
super();
// TODO Auto-generated constructor stub
System.out.println("-----无参数构造器------");
}
@Override
public String toString() {
return "Shopping [name=" + name + ", price=" + price + "]";
}
}
实现类:
public class CreateObj {
@Test
public void testIoc(){
ClassPathXmlApplicationContext cpxac= new ClassPathXmlApplicationContext("cn/spy/first/applicationContext.xml");
Shopping shopping =(Shopping) cpxac.getBean("shopping1");
System.out.println(shopping);
}
}
结果:
(2)调用带参数的构造器创建对象
配置相关的配置文件applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="str" class="java.lang.String">
<constructor-arg value="¥100"></constructor-arg>
</bean>
<bean id="shopping" class="cn.spy.pojo.Shopping">
<constructor-arg value="黄金" index="0" type="java.lang.String"/>
<constructor-arg index="1" type="java.lang.String" ref="str"/>
</bean>
</beans>
构造方法第一个参数直接通过设置值得方式来传参,而第二个参数采用的是引用的方式,通过ref来实现的。
pojo:
public class Shopping {
private String name;
private String price;
public Shopping(String name, String price) {
System.out.println("---带参数构造器--------");
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Shopping [name=" + name + ", price=" + price + "]";
}
}
实现:
public class CreateObj {
@Test
public void testIoc(){
ClassPathXmlApplicationContext cpxac= new ClassPathXmlApplicationContext("cn/spy/first/applicationContext.xml");
Shopping shopping =(Shopping) cpxac.getBean("shopping");
System.out.println(shopping);
}
}
结果:
(3).工厂类使用静态方法创建对象
配置文件applicationContext.xml :
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="shopping5" class="cn.spy.first.ObjFactory" factory-method="getStaticInstance"></bean>
<bean id="testFactory" class="cn.spy.pojo.Shopping"></bean>
</beans>
pojo:
public class Shopping {
private String name;
private String price;
public Shopping() {
super();
// TODO Auto-generated constructor stub
System.out.println("-----无参数构造器------");
}
public Shopping(String name, String price) {
System.out.println("---带参数构造器--------");
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Shopping [name=" + name + ", price=" + price + "]";
}
}
工厂类:
public class ObjFactory {
// 静态方法创建对象
public static Shopping getStaticInstance() {
return new Shopping("工厂方式创建对象","调用静态方法");
}
}
测试:
public class CreateObj {
@Test
public void testFactory(){
ApplicationContext ac =new ClassPathXmlApplicationContext("cn/spy/first/applicationContext.xml");
Shopping shopping =(Shopping) ac.getBean("shopping5");
System.out.println(shopping);
}
}
结果:
(4).工厂类使用非静态方法创建对象
配置文件applicationContext.xml :
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="factory" class="cn.spy.first.ObjFactory"></bean>
<bean id="shopping4" factory-bean="factory" factory-method="getInstance"></bean>
<bean id="testFactory" class="cn.spy.pojo.Shopping"></bean>
</beans>
pojo:
public class Shopping {
private String name;
private String price;
public Shopping() {
super();
// TODO Auto-generated constructor stub
System.out.println("-----无参数构造器------");
}
public Shopping(String name, String price) {
System.out.println("---带参数构造器--------");
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Shopping [name=" + name + ", price=" + price + "]";
}
}
工厂类:
public class ObjFactory {
// 实例方法创建对象
public Shopping getInstance() {
return new Shopping("工厂方式创建对象","调用实例方法");
}
}
测试:
public class CreateObj {
@Test
public void testFactory(){
ApplicationContext ac =new ClassPathXmlApplicationContext("cn/spy/first/applicationContext.xml");
Shopping shopping =(Shopping) ac.getBean("shopping4");
System.out.println(shopping);
}
}
结果:
5.spring的核心--依赖注入
先简单说下,分层结构:db——》dao层(对数据库进行增删改查)——》service层(对dao层返回的结果进行业务逻辑处理)——》控制层(对系统请求进行页面跳转之类的控制,数据处理由service层提供)。
我这里只是模仿下,说下注入
(1)使用XML配置注入
dao层代码:
public class UserDaoImpl{
public String getDbData(){
System.out.println("对数据库操作");
return "数据库操作结果";
}
}
service层代码:
public class UserServiceImpl{
private UserDaoImpl userDao;
public void setUserDao(UserDaoImpl userDao) {
this.userDao = userDao;
}
public void dealData(){
String dbRs =userDao.getDbData();
System.out.println(dbRs+"已经进行了逻辑处理");
}
}
解释:这里我使用的是setter方式注入,经过上面的创建对象,可以猜想到也可以通过构造器注入的。
配置文件 bean.xml :
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="userDaoRef" class="cn.spy.dao.UserDaoImpl"></bean>
<bean id="userService" class="cn.spy.service.UserServiceImpl">
<property name="userDao" ref="userDaoRef"></property>
</bean>
</beans>
测试:
public class MyTest {
@Test
public void testDi(){
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
UserServiceImpl userService =(UserServiceImpl) ac.getBean("userService");
userService.dealData();
}
}
结果:
(2)使用java注解来注入
dao层代码:
@Repository("userDao")
public class UserDaoImpl{
public String getDbData(){
System.out.println("对数据库操作");
return "数据库操作结果";
}
}
其实注解后面可以不用设置名字,但是如果以后存在多个dao,那么直接注入会让spring分不清,所以后面对应值,就给他提供了名字,以后其他的service可以通过名字注入此dao。
service层代码:
@Service("userService")
public class UserServiceImpl{
@Autowired
private UserDaoImpl userDao;
public void dealData(){
String dbRs =userDao.getDbData();
System.out.println(dbRs+"已经进行了逻辑处理");
}
}
配置文件 bean.xml :
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="cn.spy.*"></context:component-scan>
</beans>
测试类:
public class MyTest {
@Test
public void testDi(){
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
UserServiceImpl userService =ac.getBean(UserServiceImpl.class);
userService.dealData();
}
}
结果:
(3)使用 p 名称空间注入
简化了传统的注入的方式
dao层代码:
public class UserDaoImpl{
public String getDbData(){
System.out.println("对数据库操作");
return "数据库操作结果";
}
}
serivce层代码:
public class UserServiceImpl{
private UserDaoImpl userDao;
public void setUserDao(UserDaoImpl userDao) {
this.userDao = userDao;
}
public void dealData(){
String dbRs =userDao.getDbData();
System.out.println(dbRs+"已经进行了逻辑处理");
}
}
配置文件:
<?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:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="userDao" class="cn.spy.dao.UserDaoImpl"></bean>
<bean id="userService" class="cn.spy.service.UserServiceImpl" p:userDao-ref="userDao"></bean>
</beans>
测试:
public class MyTest {
@Test
public void testDi(){
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
UserServiceImpl userService =ac.getBean("userService",UserServiceImpl.class);
userService.dealData();
}
}
结果:
-------------------------
6.java代码装配bean
其实对于在很多场景下通过组件扫描和自动装备实现spring的自动化配置是更为推荐的方式。但是呢,在某些时候自动化配置方案是行不通的,需要明确配置spring。譬如,你想使用第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component和@Autowired注解的,因此就不能使用自动化配置方案了。而需要采用显式配置方案,有两种,第一种xml方式在helloworld中已经介绍,第二种使用java代码装配bean在此处介绍。
还是前面的例子的改造:
dao层实现:
public class UserDaoImpl {
public String getDbData(){
System.out.println("对数据库操作");
return "数据库操作结果";
}
}
service层实现:
public class UserServiceImpl {
private UserDaoImpl userDaoImpl;
public void setUserDaoImpl(UserDaoImpl userDaoImpl) {
this.userDaoImpl = userDaoImpl;
}
public void dealData(){
String dbRs =userDaoImpl.getDbData();
System.out.println(dbRs+"已经进行了逻辑处理");
}
}
配置类:
@Configuration
public class BeanConfig {//对于UserDaoImpl的java配置
//注解可以指定bean名称,如果未指定,那么默认就是方法名,而此处就是userDaoImpl
@Bean
public UserDaoImpl userDaoImpl(){
return new UserDaoImpl();
}
@Bean
public UserServiceImpl userServiceImpl(){
UserServiceImpl userServiceImpl =new UserServiceImpl();
userServiceImpl.setUserDaoImpl(userDaoImpl());
return userServiceImpl;
}
}
测试类:
public class MyTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(BeanConfig.class);
UserServiceImpl userServiceImpl =context.getBean(UserServiceImpl.class);
userServiceImpl.dealData();
}
}
结果:
解释:实际就是将之前的配置文件xml取消了,采用java代码配置,使用配置类来配置完成。