注解配置bean属性

2018年02月16日 16:19 | 2772次浏览

话不多说,要想用注解,必须在xml文件中添加以下内容:

<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.spring.anno"/>

base-package 属性指定扫描的基类,指定路径包及子包的类都会被自动扫描。去寻找被注解的类。如果只想扫描某些资源可以使用source-pattern去指定扫描的包如:

<context:component-scan base-package="com.spring.anno"
		resource-pattern="xxx.class"/>

配置好了就开始加注解

特定组件包括:

@Component: 基本注解, 标识了一个受 Spring 管理的组件

@Repository: 标识持久层组件

@Service: 标识业务层组件

@Controller: 标识表现层组件

其实以上四个注解的作用是一样的,之所以这么做是因为这样更能体现MVC模式,可读性提高。使用了注解后,getBean()的值该怎么填写呢?spring 有着自己默认的命名方式,就是把类名的首字母小写就可以了,当然也可以用value的值去设置,@Component(value="com"),默认可以省略value。

组件装配:

@Autowired:自动装配bean

可以直接使用在属性上,也可以使用在生产的set方法上。

话不多说,小二我就上代码了。

创建UserRepository,UserService,UserController类

package com.spring.anno.repository;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
	
	public void findUser() {
		System.out.println("这是通过注解配置bean属性的案例");
	}

}

---

package com.spring.anno.service;

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

import com.spring.anno.repository.UserRepository;

@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;
	
	public void getService(){
		System.out.print("这是service层,调用Repository方法 : ");
		userRepository.findUser();
	}

}

--

package com.spring.anno.controller;

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

import com.spring.anno.service.UserService;

@Service
public class UserController {
	
	@Autowired
	private UserService userService;
	
	public void getController(){
		System.out.print("这是controller层,调用service方法 : ");
		userService.getService();
	}

}

测试类及结果:

@Test
	public void Annotation(){
		UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
		userRepository.findUser();
		UserService userService = (UserService) ctx.getBean("userService");
		userService.getService();
		UserController userController = (UserController) ctx.getBean("userController");
		userController.getController();
	}

--

这是通过注解配置bean属性的案例
这是service层,调用Repository方法 : 这是通过注解配置bean属性的案例
这是controller层,调用service方法 : 这是service层,调用Repository方法 : 这是通过注解配置bean属性的案例

亲测可用,由于疏忽大意,报了一个错误:

Error creating bean with name 'userController': Injection of autowired dependencies failed........

最后才发现是UserRepository上没有添加@Repository注解


以下是补充内容,我用的比较少理解不是很深刻,如果读者有什么意见和看法可以留言,我会及时更正

<context:include-filter> 子节点表示要包含的目标类

<context:exclude-filter> 子节点表示要排除在外的目标类 ,需要在context:component-scan中设置user-default-filters = "false",默认是true

type: 有annotation(根据注解)和assinable(根据继承和扩展)

expression指定路径



小说《我是全球混乱的源头》

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程