spring如何实现依赖注入DI(spring

网友投稿 383 2022-08-22


spring如何实现依赖注入DI(spring

目录spring依赖注入DI1、创建一个maven项目2、修改pom.xml3、添加类Person和Body4、在配置类App中,添加ComponentScan5、新建一个测试类6、运行测试类7、从运行结果中我们能看到spring-test依赖无法使用问题

spring依赖注入DI

1、创建一个maven项目

mvn archetype:generate -DarchetypeCatalog=internal

2、修改pom.xml

引入需要的依赖,aHekoeEof首先spring-context,还是spring-test,最后还有junit。

UTF-8

4.3.7.RELEASE

junit

junit

4.12

test

org.springframework

spring-context

${springframework.version}

org.springframework

spring-test

${springframework.version}

org.apache.maven.plugins

maven-compiler-plugin

1.8

1.8

utf-8

maven-assembly-plugin

<version>3.0.0

com.xueyoucto.xueyou.App

jar-with-dependencies

make-assembly

package

single

3、添加类Person和Body

package com.xueyou.demo;

import org.springframework.stereotype.Component;

@Component

public class Person {

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private String name;

}

package org.xueyou.demo;

import org.springframework.stereotype.Component;

@Component

public class Body {

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

private int id;

}

4、在配置类App中,添加ComponentScan

需要注意的是,这里需要指定扫描的包

package com.xueyou.demo;

import org.springframework.contexthttp://.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

/**

* Hello world!

*/

@Configuration

@ComponentScan(basePackages = {"org.xueyou.demo","com.xueyou.demo"})

public class App {

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

5、新建一个测试类

package com.xueyou.demo;

import org.junit.Assert;

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 org.xueyou.demo.Body;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = App.class)

public class Springtest {

@Autowired

private Body body;

@Autowired

private Person person;

@Test

public void testBodyIsNull(){

Assert.assertNotNull(body);

}

@Test

public void testPersonIsNull(){

Assert.assertNotNull(person);

}

}

6、运行测试类

结果如下:

7、从运行结果中我们能看到

Person类和Student类已经被依赖注入到spring中,spring能够使用这两个类了。

spring-test依赖无法使用问题

org.springframework

spring-aHekoeEoftest

4.3.7.RELEASE

test

去掉

test


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用 mybatis 自定义日期类型转换器的示例代码
下一篇:Web三大组件之Filter,Listener和Servlet详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~