标签:scan ioc http spring 依赖 name tco cti ati
Spring是一个基于IOC和AOP的结构J2EE系统的框架
反转控制,Inversion of Control.将new方式创建对象变为交给Spring创建对象.
DI 依赖注入 Dependency Inject.会在生成的对象中注入默认值.
<?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 name="c" class="pojo.Category">
<property name="name" value="category 1" />
</bean>
</beans>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "spring-config.xml" });
Category c = (Category) context.getBean("c");
System.out.println(c.getName());
}
<bean name="p" class="com.how2java.pojo.Product">
<property name="name" value="product1" />
<property name="category" ref="c" />
</bean>
注解方式:
<context:annotation-config/>
<bean name="c" class="com.how2java.pojo.Category">
<property name="name" value="category 1" />
</bean>
<bean name="p" class="com.how2java.pojo.Product">
<property name="name" value="product1" />
</bean>
在Product的category属性或者setCategory()方法前加上@Autowired注解
或者在category属性前加上@Resource(name="c")注解
1.新增
2.在每个bean的类声明前加上@Component("name")标明此类是bean.初始化写在属性声明中.
面向切面编程.为了让不同的逻辑分离开来可以分别处理,AOP是必要的.AOP将程序的逻辑按不同的方面来看待,将程序逻辑划分为几个不同的切面.每个切面分别实现自己相关的逻辑,然后通过Spring整合到一起.这样做的好处在于每个方法都可以只关心自己负责的逻辑,方便了维护和使用,减少了代码的重复.
配置业务类:Component表示是bean,交给spring管理
@Component("s")
public class ProductService {
public void doSomeService(){
System.out.println("doSomeService");
}
}
配置切面@Aspect表示是切面,@Around表示切入ProductService类的所有方法.
@Aspect
@Component
public class LoggerAspect {
@Around(value = "execution(* com.how2java.service.ProductService.*(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("start log:" + joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
System.out.println("end log:" + joinPoint.getSignature().getName());
return object;
}
}
配置xml
<context:component-scan base-package="com.how2java.aspect"/>
<context:component-scan base-package="com.how2java.service"/>
<aop:aspectj-autoproxy/>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class testSpring {
@Autowired
Category c;
@Autowired
ProductService s;
@Test
public void test() {
// System.out.println(c.getName());
s.doSomeService();
}
}
标签:scan ioc http spring 依赖 name tco cti ati
原文地址:https://www.cnblogs.com/bestefforts/p/11351317.html