Spring一些常见的使用方法

一.在Spring中注入Bean属性的值

也可以为Bean属性注入数组值:

<property name="xxx">
    <array>
        <value>element-value-1</value>
        <value>element-value-2</value>
    </array>
</property>

二.Spring表达式
1.Spring表达式可以应用于Spring的XML配置文件中。
使用Spring表达式可以在注入值时,引用另一个Bean的属性值,或另一个Bean中的集合中的某个元素……
使用条件:某个BeanX已经被注入值,另一个BeanY的某些值来自于BeanX。

2.Spring表达式的基本格式是:
(1)#{被引用bean的id.属性名称 }
如果引用的是数组或List集合中的某个元素,则:
(2)#{被引用bean的id.数组名或集合名称[下标] }
如果引用的是Map或Properties,则:
(3)#{被引用bean的id.Map名或Properties名.key},
或:
#{被引用bean的id.Map名或Properties名['key']}

<bean id="target" class="cn.tedu.spring.bean.TargetBean">
    <property name="id" value="#{source.id}"></property>
    <property name="name" value="#{source.name}"></property>
    <property name="city" value="#{source.cities[2]}"></property>
    <property name="role" value="#{source.session.role}"></property>
    <property name="driver" value="#{source.dbConfig['driver']}"></property>
</bean>


三.Spring的自动装配(AutoWire)——UserService里有设置userDao属性的方法
1.Spring的自动装配表现为可以自动注入的值,而不需要在XML中通过Set方式或构造方法来进行注入!
<bean id="userService" class="cn.tedu.spring.service.UserService" autowire="byName" />
2.在XML配置中,节点中的autowire属性的值可以是:
(1)no:默认值,不会自动装配。
(2)byName:根据属性名完成自动装配,要求在XML文件中也存在相同名称的<bean id="属性名称">的配置,如果没有对应的<bean>,将不会自动装配,也不会报告错误。
(3)byType:根据属性的类型完成自动装配,要求在XML文件存在与属性的类型相同的Bean的配置,这样的做法对于<bean>的id并没有要求!**注意:如果类型能够匹配到2个或者更多的<bean>则会导致程序崩溃!!!**
(4)constructor:基于构造方法,模式可参考byType
(5)autodetect:自动检测

<bean id="userDao" class="cn.tedu.spring.dao.UserDaoImpl"/>
<!--<bean id="userDao2" class="cn.tedu.spring.dao.UserDaoImpl2" /> -->
<bean id="userService" class="cn.tedu.spring.service.UserService" autowire="byType"/>

3.使用Autowire可以简化开发,避免XML配置文件过于臃肿,也可以避免可能存在的的调整,
例如出于某种原因修改了的id,但是,也存在之间的依赖关系表现得不明确的问题!


四.context:component-scan子节点的使用
1.配置base-package属性,该属性的值是希望Spring管理的那些类在哪个包中!
<context:component-scan base-package="cn.tedu.spring" />
注:配置包的时候,不一定是精确的指向某个类所在的包,可以是更加父级的包名,例如cn.tedu.spring也是可以的,那么,在cn.tedu.spring.bean或cn.tedu.spring.dao等这些包中的类都将被Spring管理!

2.在需要被Spring管理的类的声明上方添加 @Component 的注解。
3.当Spring扫描到cn.tedu.spring.bean.User类后,会自动根据类名决定将生成的的id为user,即类名的首字母小写后,就是的id,完成节点的配置!
4.@Component("u")
public class User { }

5.常用于类的注解
(1)@Component:通用注解
(2)@Named:通用注解,不推荐
(3)@Controller:控制器的注解
(4)@Service:业务逻辑的注解
(5)@Respository:持久层的注解

6.取代节点配置的注解
(1)以下注解用于对类的声明进行注解
@Scope / @Scope(“singleton”) / @Scope(“prototype”)
@Lazy


(2)以下注解用于对类中的方法的声明进行注解
@PostConstruct
@PreDestroy


7.使用注解实现自动装配(优先使用@Resource注解)
(1)使用@Autowired和@Qualifier的组合可以实现自动装配:
这种组合方式不仅仅可以用于基于Set的注入,也可以用于基于构造方法的注入!
@Autowired
public void setUserDao(@Qualifier("userDao") IUserDao userDao) {
    this.userDao = userDao;
}

(2)可以直接应用于需要注入的属性:
@Autowired
@Qualifier("userDao")
private IUserDao userDao;

(3)使用@Resource也可以实现属性的注入
@Resource
private IUserDao userDao;
或者:
@Resource(name="userDao")
private IUserDao userDao;

(4)直接注入值
使用@Value注解可以注入值,例如:
@Value("hello")
private String name;
使用@Value注解时,也支持Spring表达式,即:
@Value(Spring表达式)

8.注解汇总
@Componenet
@Scope
@Lazy
@PostConstruct
@PreDestory
@Autowired
@Qualifier
@Resource
@Value

五.同一包下注解使用实例:
1.resources下的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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    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
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
	<context:component-scan base-package="cn.tedu.spring.bean"></context:component-scan>
    
</beans>

2.各种用户类:

package cn.tedu.spring.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Component;

@Component("u")
public class User {
	
	public User() {
		System.out.println("User()");
	}
	
	@PostConstruct
	public void init() {
		System.out.println("User.init()");
	}
	
	@PreDestroy
	public void destroy() {
		System.out.println("User.destroy()");
	}

}

package cn.tedu.spring.bean;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class SingletonUser {

	public SingletonUser() {
		System.out.println("SingletonUser()");
	}

}

package cn.tedu.spring.bean;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class PrototypeUser {

	public PrototypeUser() {
		System.out.println("PrototypeUser()");
	}

}

package cn.tedu.spring.bean;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class LazyUser {

	public LazyUser() {
		System.out.println("LazyUser()");
	}
	
}

3.测试类:

package cn.tedu.spring.test;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.tedu.spring.bean.LazyUser;
import cn.tedu.spring.bean.PrototypeUser;
import cn.tedu.spring.bean.SingletonUser;
import cn.tedu.spring.bean.User;

public class Test {

	public static void main(String[] args) {
		String file = "applicationContext.xml";
		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(file);
		System.out.println("加载配置完成!\n");

		User user = ctx.getBean("u", User.class);
		System.out.println(user);
		System.out.println();
		
		SingletonUser su1 = ctx.getBean("singletonUser", SingletonUser.class);
		SingletonUser su2 = ctx.getBean("singletonUser", SingletonUser.class);
		System.out.println(su1);
		System.out.println(su2);
		System.out.println();
		
		PrototypeUser pu1 = ctx.getBean("prototypeUser", PrototypeUser.class);
		PrototypeUser pu2 = ctx.getBean("prototypeUser", PrototypeUser.class);
		System.out.println(pu1);
		System.out.println(pu2);
		System.out.println();
		
		LazyUser lu = ctx.getBean("lazyUser", LazyUser.class);
		System.out.println(lu);
		System.out.println();
		
		System.out.println("准备释放资源...");
		ctx.close();
		System.out.println("释放资源完成!");
	}

}

4.程序运行结果如下:
SingletonUser()
User()
User.init()
加载配置完成!

cn.tedu.spring.bean.User@33f88ab

cn.tedu.spring.bean.SingletonUser@27a8c74e
cn.tedu.spring.bean.SingletonUser@27a8c74e

PrototypeUser()
PrototypeUser()
cn.tedu.spring.bean.PrototypeUser@1b68ddbd
cn.tedu.spring.bean.PrototypeUser@646d64ab

LazyUser()
cn.tedu.spring.bean.LazyUser@536aaa8d

准备释放资源...
User.destroy()
释放资源完成!


六.不同包同父类包注解的使用
1.resources下的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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    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
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
	<context:component-scan base-package="cn.tedu.spring"></context:component-scan>
    
</beans>

2.用户类

package cn.tedu.spring.dao;

public interface IUserDao {
	public void insert();
}

package cn.tedu.spring.dao;

import org.springframework.stereotype.Component;

@Component("userDao")
public class UserDaoImpl implements IUserDao{

	public void insert() {
		System.out.println("UserDaoImpl.insert()");
	}

}

3.用户生产类

package cn.tedu.spring.service;

public interface IUserService {
	public void reg();
}

package cn.tedu.spring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.tedu.spring.dao.IUserDao;

@Component("userService")
public class UserServiceImpl implements IUserService{
	@Autowired
	@Qualifier("userDao")
	private IUserDao userDao;
	
	public void reg() {
		System.out.println("UserServiceImpl.reg()");
		userDao.insert();
	}
	
}

4.测试类

package cn.tedu.spring.test;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.tedu.spring.service.IUserService;

public class Test {

	public static void main(String[] args) {
		String file = "applicationContext.xml";
		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(file);
		
		IUserService userService = ctx.getBean("userService", IUserService.class);
		userService.reg();
		
		ctx.close();
	}

}

5.运行结果如下
UserServiceImpl.reg()
UserDaoImpl.insert()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsa_pursuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值