spring自动装配和aop的理解
Posted zipon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring自动装配和aop的理解相关的知识,希望对你有一定的参考价值。
1.自动装配,有用到这个自动装配的时候,就去扫描包,spring把带有@Component和@Bean的自动实例。
package bean; import org.springframework.stereotype.Component; /** * Created by zipon on 2017/7/15. */ @Component public class Task { private String taskId ; private String taskName ; public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public String toString() { return "Task{" + "taskId=‘" + taskId + ‘\‘‘ + ", taskName=‘" + taskName + ‘\‘‘ + ‘}‘; } public void getTask(){ System.out.println("=============>renwushi=======>"+"renwuId:"+taskId+",renwuname:"+taskName); } }
通过@Configuration创建设置类,通过@ComponentScan(basePackageClasses = {Task.class})扫描Task.class所在的包。
package springTest; import bean.Task; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; /** * Created by zipon on 2017/7/15. */ @Configuration @ComponentScan(basePackageClasses = {Task.class}) public class ComponentConfig { }
通过@ContextConfiguration(classes = ComponentConfig.class)导入配置
package springTest; import bean.Task; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /** * Created by zipon on 2017/7/15. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ComponentConfig.class) public class AutowiredTest { @Autowired private Task task; @Test public void test(){ System.out.println(task.toString()); task.getTask(); assertNotNull(task); } }
以上是关于spring自动装配和aop的理解的主要内容,如果未能解决你的问题,请参考以下文章
框架 day36 Spring3 入门,DI依赖注入,装配bean基于xml/注解, 整合Junit4,配置约束自动提示