首页 > 其他分享 >【Spring】装配Bean 组件扫描

【Spring】装配Bean 组件扫描

时间:2022-12-09 12:07:10浏览次数:38  
标签:Spring public test Bean Inject import 组件 org class


实现自动装配需要用注解:注解分为 spring规范和java规范 ,java规范需要引入javax.inject 包 ,使用maven,直接引入。

从中可以看到 @Named @Inject属于java规范,@Component  @Autowired @Resource属于spring注解

@Named大致等效于@Component 而@Inject和@Autowired也相似,但是@Inject要强制注入,@Autowired(required=false)可以选择略过不报异常

【Spring】装配Bean 组件扫描_Test




实例:

1.写个bean接口

package test.soundsystem;

public interface CompactDisc {
void play();
}

2.实现接口

package test.soundsystem;

import javax.inject.Named;

@Named
public class SgtPeppers implements CompactDisc {

private String title="Sgt. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles";
public void play() {
System.out.println("Playing "+title+" by "+artist);
}
}

3.自动装配类

package test.soundsystem;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import test.voice.Book;

@Configuration
@ComponentScan(basePackageClasses={Book.class,CompactDisc.class})
public class CDPlayerConfig {
}


4.测试类:

package test.soundsystem;

import javax.inject.Inject;

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 test.voice.Book;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
@Autowired
private CompactDisc cd;

@Inject
private Book book;

@Test
public void cdShouldNotBeNull(){
cd.play();
book.read();
}
}



测试结果:

【Spring】装配Bean 组件扫描_Test_02




标签:Spring,public,test,Bean,Inject,import,组件,org,class
From: https://blog.51cto.com/u_15907520/5924533

相关文章