码迷,mamicode.com
首页 > 编程语言 > 详细

spring自动装配和aop的理解

时间:2017-07-15 10:09:54      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:alt   zip   his   type   创建   can   建设   one   pack   

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);
    }
}
View Code

通过@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的理解

标签:alt   zip   his   type   创建   can   建设   one   pack   

原文地址:http://www.cnblogs.com/zipon/p/7176649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!