Spring框架
1.Spring框架
创建一个
改变配置文件
<!-- 把我們要在應用程序中的類的對象要配置出來 配置進容器中 -->
<bean id="userDao" class="cn.ybzy.springdemo.dao.UserDaoImpl"></bean>
<bean id="user" class="cn.ybzy.springdemo.model.User">
<property name="username" value="admint"></property>
<property name="password" value="admint123"></property>
<property name="id" value="123"></property>
</bean>
在对应需要new对象的地方
// spring
// 1. 先拿到spring ioc 容器
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.通過容器 可以拿到我們想要的類的對象實例
User user = ctx.getBean(User.class);
UserDao userDao = ctx.getBean(UserDao.class);
// 3.根據獲取的對象的實例。調用方法
userDao.add(user);
运行结果为:
杂记
<?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">
<!-- 把我们在应用程序类中要使用的类的对象实例,配置进Spring的IOC的容器里 -->
<!-- 让 Spring 在底层创建一个UserDaoImpl类型的对象,放到IOC的容器里等待java代码的使用 -->
<bean id="userDao" class="cn.ybzy.springdemo.dao.UserDaoImpl"></bean>
<!-- 让 Spring 在底层创建一个UserServiceImpl类型的对象,放到IOC的容器里等待java代码的使用 -->
<!-- 创建这个对象的时候,还把刚刚创建的UserDaoImpl类型的对象注入到UserServiceImpl里的userDao属性的值 -->
<bean id="userService"
class="cn.ybzy.springdemo.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
用于解除耦合,所有东西都放在了这里来进行设置
练习1
public class User {
private int id;
private String username;
private String password;
private Map<String,String>map=new HashMap<>();
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public int getId() {
return id;
}
<?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 id="user" class="com.neusoft.spring.model.User">
<property name="id" value="123"></property>
<property name="username" value="zhangsan"></property>
<property name="password" value="admin"></property>
<property name="map">
<map>
<entry key="Hibernate" value="95"></entry>
<entry key="Spring" value="95"></entry>
<entry key="SpringMvc" value="95"></entry>
</map>
</property>
</bean>
<bean id="userDao" class="com.neusoft.spring.dao.UserDaoImpl"></bean>
<bean id="userService" class="com.neusoft.spring.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
注入的标签为set 或者 list
<list>
<value>123</value>
<value>123</value>
<value>123</value>
</list>
package com.neusoft.spring.text;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.neusoft.spring.model.User;
import com.neusoft.spring.service.UserService;
public class Text {
@Test
public void text() {
ApplicationContext cxt=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=(User) cxt.getBean("user");
System.out.println(user.getMap());
}
}
有参构造注入形式
package com.neusoft.spring.service;
import com.neusoft.spring.dao.UserDao;
import com.neusoft.spring.model.User;
public class UserServiceImpl implements UserService {
private UserDao userDao;
private String a;
public UserServiceImpl(UserDao userDao,String a) {
this.userDao=userDao;
this.a=a;
}
@Override
public void add(User user) {
// TODO Auto-generated method stub
// userDao.add(user);
System.out.println(userDao);
System.out.println(a);
}
}
<?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 id="user" class="com.neusoft.spring.model.User">
<property name="id" value="123"></property>
<property name="username" value="zhangsan"></property>
<property name="password" value="admin"></property>
<property name="map">
<map>
<entry key="Hibernate" value="95"></entry>
<entry key="Spring" value="95"></entry>
<entry key="SpringMvc" value="95"></entry>
</map>
</property>
</bean>
<bean id="userDao" class="com.neusoft.spring.dao.UserDaoImpl"></bean>
<bean id="userService" class="com.neusoft.spring.service.UserServiceImpl">
**<constructor-arg ref="userDao"></constructor-arg>
<constructor-arg value="sdfaf"> </constructor-arg>**
</bean>
</beans>
内部been
<?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 id="user" class="com.neusoft.spring.model.User">
<property name="id" value="123"></property>
<property name="username" value="zhangsan"></property>
<property name="password" value="admin"></property>
<property name="map">
<map>
<entry key="Hibernate" value="95"></entry>
<entry key="Spring" value="95"></entry>
<entry key="SpringMvc" value="95"></entry>
</map>
</property>
</bean>
<!-- <bean id="userDao" class="com.neusoft.spring.dao.UserDaoImpl"></bean> -->
<bean id="userService" class="com.neusoft.spring.service.UserServiceImpl">
<constructor-arg >
<bean class="com.neusoft.spring.dao.UserDaoImpl"></bean>
</constructor-arg>
<constructor-arg value="sdfaf"></constructor-arg>
</bean>
</beans>
特殊类型的注入
<?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 id="user" class="com.neusoft.spring.model.User">
<property name="id" value="123"></property>
<property name="username" value="zhangsan"></property>
<property name="password" value="admin"></property>
<property name="map">
<map>
<entry key="Hibernate" value="95"></entry>
<entry key="Spring" value="95"></entry>
<entry key="SpringMvc" value="95"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="password">root</prop>
</props>
</property>
</bean>
<!-- <bean id="userDao" class="com.neusoft.spring.dao.UserDaoImpl"></bean> -->
<bean id="userService" class="com.neusoft.spring.service.UserServiceImpl">
<constructor-arg >
<bean class="com.neusoft.spring.dao.UserDaoImpl"></bean>
</constructor-arg>
<constructor-arg value="sdfaf"></constructor-arg>
</bean>
</beans>
自动装载
继承与依赖
1.继承 在bean 标签中加入关键字 parent 属性 继承父类的相同属性,可以被重写
在bean 可以写一个专门的模板,使用关键字 abstravt=true 这样父类不会被实例
2.依赖 在bean 标签中加入 depends on="" 关键字,依赖使用后被依赖的没有实例的时候 会报错
可以和关联一起使用 关键字 ref
<bean id="pet" class="com.neusoft.spring.model.Pet">
<property name="id" value="123"></property>
<property name="type" value="xiaohua"></property>
</bean>
<bean parent="pet" id="dog">
<property name="id" value="223"></property>
<property name="type" value="xiaogou"></property>
</bean>
<bean id="persion" class="com.neusoft.spring.model.persion"
depends-on="pet" >
<!-- 依赖这个pet这个对象 -->
<property name="id" value="12" ></property>
<!-- 关联属性 不关联的话结果为NULL -->
<property name="pet" ref="pet"></property>
</bean>
bean 作用域的相关配置
关键字,scope 中的 prototype 表示实例对象不是单例 singleton 默认的 为单例
外部文件导入
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="jdbcUrl" value="jdbc:mysql://Localhost:3306/db01"></property>
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
</bean>
不建议这么写
spring的表达式语言spEL
ref="#{}" --来替换掉
value="#{pet.map[1]}"
value="#{pet.list[0]}"
在里面可以使用加减运算,逻辑符号,正则表达式,三元运算等等…
命名空间粗暴解决方案
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.nuesoft.SpringText729" />
</beans>
spring框架注解的使用
@Component //给类注解
@Service //服务层注解
@Controller //控制层注解
@Repository //dao层注解
@Scope(scopeName = "singletion") //单例
@Value(value = "188") // 方法属性上的赋值
@Resource(name = "car") //等同于ref 相关联
@Autowired //自动装配 使用的情况下相关联的对象,一定要被实例化,主要是通过type>name 进行查找
//可以在这里面 @Autowired(required=false) //表示如果没有这个类的话也不报错
使用注解的话 可以省去使用get set 方法的,注解的使用需要按照上述的操作进行配置 <context:component-scan base-package=“com.nuesoft.SpringText729” />
@Autowired
@Qualifier("bwnCar")
接口类型的多个对象的时候可以使用@Qualifier 注解来确定具体哪个
标签的作用
<context:component-scan base-package="com.neusoft.spring.model" > </context:component-scan>
1.可以配置多个包用逗号分开
<context:component-scan base-package="com.neusoft.spring.model" resource-pattern="model/*.class" ></context:component-scan> //只扫描model下面的所有class
<context:component-scan base-package="com.neusoft.spring.model" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> //排外Controller
</context:component-scan>
日志的使用
package com.neusoft.aop;
import org.apache.log4j.Logger;
public class Run {
private static Logger logger = Logger.getLogger(Run.class);
public static void main(String[] args) {
add(1,5);
sub(4,1);
div(10,2);
}
public static int add(int i, int j) {
// log4j 这个日志框架,日志的信息有五个级别 fatal(最高) error warn info debug
logger.info("add方法运算");
int a = i + j;
logger.info("add运算之后" + a);
return a;
}
public static int sub(int i, int j) {
// log4j 这个日志框架,日志的信息有五个级别 fatal(最高) error warn info debug
logger.info("add方法运算");
int a = i - j;
logger.info("add运算之后" + a);
return a;
}
public static int div(int i, int j) {
// log4j 这个日志框架,日志的信息有五个级别 fatal(最高) error warn info debug
logger.info("add方法运算");
int a = i / j;
logger.info("add运算之后" + a);
return a;
}
}
### set log levels ###
log4j.rootLogger=debug,stdout,D
## CONSOLE Appender ##
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %n %d %p [%1] %m %n
## out file ##
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File=./log4j.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern= %n %d %p [%1] %m %n
日志项目使用方式
package com.neusoft.spring.aop;
public interface AopText {
public int add(int i, int j) ;
public int sub(int i, int j) ;
public int div(int i, int j) ;
}
package com.neusoft.spring.aop;
import org.springframework.stereotype.Component;
@Component("aopText")
public class AopTextImpl implements AopText {
@Override
public int add(int i, int j) {
// TODO Auto-generated method stub
int a = i + j;
return a;
}
@Override
public int sub(int i, int j) {
// TODO Auto-generated method stub
int a = i - j;
return a;
}
@Override
public int div(int i, int j) {
// TODO Auto-generated method stub
int a = i / j;
return a;
}
}
package com.neusoft.spring.aop;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component("loggerAspect")
public class LoggerAspect {
private Logger logger = Logger.getLogger(this.getClass());
// 提取出来 所有切入点的表达式
@Pointcut("execution(public * *(..))")
public void commonExecution() {
}
// 选择执行哪个
@Before("commonExecution")
public void beforeMethod(JoinPoint joinPoint) {
// 获取切面点的方法信息
String name = joinPoint.getSignature().getName();
// 切入点的方法参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
logger.info(name + "xxxx方法运行之前" + args);
}
@After("commonExecution")
public void afterMethod(JoinPoint joinPoint) {
// 获取切面点的方法信息
String name = joinPoint.getSignature().getName();
// 切入点的方法参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
logger.info(name + "xxxx方法运行之后" + args);
}
@AfterThrowing(value = "commonExecution" ,throwing="ex")
public void throwMethod(JoinPoint joinPoint ,Exception ex) {
// 获取切面点的方法信息
String name = joinPoint.getSignature().getName();
// 切入点的方法参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
logger.info(name + "xxxx方法运行之后" + args+ex);
}
}
package com.neusoft.spring.aop;
import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Run {
private static Logger logger = Logger.getLogger(Run.class);
public static void main(String[] args) {
ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
AopText aopText = (AopText) cxt.getBean("aopText");
System.out.println("add" + aopText.add(1, 1));
System.out.println("sub" + aopText.sub(7, 1));
System.out.println("div" + aopText.div(10, 1));
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启Spring的注解 有注解的范围 -->
<context:component-scan base-package="com.neusoft.spring.aop" > </context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
以上完了
@Aspect //告知Spring容器 我是一个切面
@Before //前置通知
@After //后置通知
@AfterReturning //返回通知
@AfterThrowing //异常通知
@Around //环绕通知
xml配置
<!-- 开启Spring的注解 有注解的范围 -->
<context:component-scan
base-package="com.neusoft.spring.aop">
</context:component-scan>
<aop:config>
<!-- 切面点表达式 -->
<aop:pointcut expression="execution(* com.neusoft.spring.aop.*.*(..))" id="pointcut" />
<aop:aspect ref="loggerAspect" order="1">
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<aop:after-throwing method="throwMethod" pointcut-ref="pointcut" throwing="rs"></aop:after-throwing>
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
</aop:aspect>
</aop:config>