spring实战-注解装配bean

spring提供的基于xml的bean装配并不受所有人的欢迎,实际上很多开发人员排斥太多的xml配置,spring还提供了基于注解的bean申明和装配,事实上该种方式也是目前最普遍受欢迎的方式

spring-beans.xml



	
	
	
	
	
	
	
	
	
		
		
	
	

TestMain

package com.halfworlders.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Primary 注解 设置首选bean
 * @Qualifier 注解设置限定符
 * @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) 注解设置作用域
*/
class TestMain3 {
	@SuppressWarnings({ "resource", "unused" })
	
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-beans.xml");  
        Object proxy = applicationContext.getBean("proxyInfo");  
        Object connection = applicationContext.getBean("connection");  
        Object service = applicationContext.getBean("service");  
        System.out.println("-----end------");  
	}
}


ProxyInfo

package com.halfworlders.web;

import org.springframework.stereotype.Component;

/*
 * 当为Component注解指定参数时,该Bean的ID就是参数值
 * 如果没有指定参数,默认就为类名首字母小写作为ID值
 */
@Component("proxyInfo")
public class ProxyInfo {
	private String ip;
	private int port;
	
	get..set..
}


Config

package com.halfworlders.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Config {
	
	/*
	 * 可以通过Value装配任何类型的值,包括基本类型等硬编码的值,但是这样做并没有什么意义
	 * 但是Value注解可以使用SpEL表达式
	 * 特别的是,在项目中我们经常通过Value注解将properties文件的配置参数注入到系统中
	 */
	@Value("5")
	private int timeOut;

	get...set...
	
}

Connection

package com.halfworlders.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * autowired注解注入,必须保证有且只有一个可以匹配的bean,否则会报异常
 * 但是也都有对应的方法,避免异常:1,可选的自动装配;2,限定歧义性依赖
 */
@Component
public class Connection {

	/*
	 * 基于属性的注解注入,autowired注解的注入不会受限于private关键字
	 * 1,required=false可选的自动装配,如果没有可以匹配的bean,这proxyInfo为null值
	 * 2,Qualifier可以帮助限定歧义性依赖,如果有多个可以匹配的bean,可以通过Qualifier制定bean的名字(ID)来注入
	 */
	@Autowired(required=false)
	@Qualifier("proxyInfo")
	private ProxyInfo proxyInfo;
	
	private Config config;
	
	public Connection(){
	}
	

	/*
	 * 基于属性set函数的注解注入
	 */
	@Autowired
	public void setConfig(Config config) {
		this.config = config;
	}
	
	get...set...

}

Service

package com.halfworlders.web;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Service {
	private Connection connection;
	private List urls;
	private Map response;
	
	public Service() {
		
	}
	
	/*
	 * 基于构造函数的注解注入
	 * 当autowired标注多个构造函数时,系统会选择参数最多的那个构造器
	 */
	@Autowired
	public Service(Connection connection) {
		this.connection = connection;
	}
	
	get...set...
}



你可能感兴趣的:(spring)