Spring - 裝配Spring Bean-通過註解(自動裝配-@Autowired)

通過註解裝配Spring Bean(自動裝配-@Autowired)

自動裝配-@Autowired

在上一節中還有一個對象注入問題沒有解決,關於這個問題,在大部分情況下建議使用自動裝配,可以減小配置的複雜度。
通過學習Spring IOC容器,我們知道Spring是先完成Bean的定義和生成,然後當Spring生成所有的Bean後,如果發現註解@AutoWired,他就會在Bean中查找,然後找到對應的類型,將其注入。

實現自動裝配

  • 定義實體類,Role.java
package com.ssm.annotation.pojo;

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

@Component(value = "role")
public class Role {
	@Value("1")
	private Long idLong;
	
	@Value("roleName1")
	private String roleNameString;
	
	@Value("note1")
	private String noteString;
	/*省略get和set方法*/
}
  • 生成一個Service接口
package com.ssm.annotation.service;

public interface RoleService {
	public void printRoleInfo();
}
  • 生成Service接口實現類
package com.ssm.annotation.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ssm.annotation.pojo.Role;
import com.ssm.annotation.service.RoleService;

@Component
public class RoleServiceImpl implements RoleService{

	@Autowired
	private Role role = null;
	
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	@Override
	public void printRoleInfo() {
		System.out.println("RoleServiceImpl"+role.toString());
	}
}

這裏的註解@AutoWired,表示在Spring IOC中定位的所有Bean後,到Sring IOC容器中按照類型查找對應的實例並將其注入。

  • 掃描組件類
package com.ssm.annotation.config;

import org.springframework.context.annotation.ComponentScan;
import com.ssm.annotation.pojo.Role;
import com.ssm.annotation.service.impl.RoleServiceImpl;

@ComponentScan(basePackageClasses = {Role.class,RoleServiceImpl.class},basePackages = {"com.ssm.annotation.pojo","com.ssm.annotation.service"})
public class PojoConfig {}
  • 測試類
package com.ssm.annotation.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.ssm.annotation.config.PojoConfig;
import com.ssm.annotation.pojo.Role;
import com.ssm.annotation.service.RoleService;

public class AnnotationTest {
	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(PojoConfig.class);
		Role role = context.getBean(Role.class);
		RoleService roleService =context.getBean(RoleService.class);
		roleService.printRoleInfo();
	}
}
  • 測試結果
RoleServiceImplRole [idLong=1, roleNameString=roleName1, noteString=note1]

:@AutoWired註解除了可以配置在屬性上之外,還可以配置到方法上

@Component
public class RoleServiceImpl implements RoleService{
	private Role role = null;
	public Role getRole() {
		return role;
	}
	
	@Autowired
	public void setRole(Role role) {
		this.role = role;
	}
	
	@Override
	public void printRoleInfo() {
		System.out.println("RoleServiceImpl"+role.toString());
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章