Springboot实战第四天:(1)spring常用注解分析-2019-8-20

本文深入探讨Spring框架中的注解配置与Java配置,详细解释了@Component、@Service、@Repository、@Controller等注解的使用场景,以及@Autowired、@Inject、@Resource等bean注入注解的应用。同时,介绍了如何通过@Configuration和@Bean实现Java配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我们Java开发中,Spring  Ioc容器(ApplicationContext)负责创建bean,并通过容器将功能类Bean注入到所需要的bean中,xml配置,注解配置还是Java配置都称为配置元数据元数据就是描述数据的数据,Spring容器解析这些配置元数据进行bean初始化 ,配置,管理依赖。

声明Bean的注解:以下四个注解是等效的,只是在不同的逻辑层使用对应的注解比较一目了然

        @Component组件,没有明确的角色,可以代表后面三个注解

        @Service   在业务逻辑层(service层)使用

        @Repository  在数据访问层(dao层)使用

         @Controller  在表现层(MVC-->SpringMVC)使用

注入bean的注解:

       @Autowired:spring提供的注解

       @Inject:jsr-330提供的注解

        @Resource:jsr-250提供的注解

@Autowired   @Inject    @Resource可以注解在set方法上或者属性上面,建议将注解使用在属性上,有时就是代码更少,层次更清晰

具体项目实践如下:以下所有的类均在同一个包下

package com.itcast.springboot.annotation;

import org.springframework.stereotype.Service;

@Service
public class FunctionService {
	public String sayHello(String word){
		return "hello world !spring Annotation!"+word;
		
	}
}
package com.itcast.springboot.annotation;

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

@Service
public class UseFunctionService {
		@Autowired
		FunctionService functionService;
		
		public String sayHello(String word){
			return functionService.sayHello(word);
		}
}

 

只是实践注解配置类,实际并没有配置什么

package com.itcast.springboot.annotation;

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

@Configuration
@ComponentScan("com.itcast.springboot.annotation")
public class DIConfig {

}

package com.itcast.springboot.annotation;

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

public class SpringApp {
	public static void main(String[] args) {
		ApplicationContext  context=new AnnotationConfigApplicationContext(DIConfig.class);
		UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
		System.out.println(useFunctionService.sayHello("di"));
		((AbstractApplicationContext) context).close();
	}
}

运行结果:

此次就把上几篇博客里面没有提到的常用的比较重要的注解都解释了一遍。注解会用之后会发现写的代码很简洁。

以上是分析的还是注解配置,不过Java配置也是springboot中比较推荐的一种方式,其实现方式是通过@Configuration和@Bean

 

使用Java配置和注解混合配置是根据项目中不同的场合采取的比较灵活的一种配置方式,至于什么地方使用Java配置,什么场合使用注解:

今天的内容就分析了Java配置和注解,下一期讲一下Spring  AOP面向切面的内容。

不急跬步无以至千里,不积小流无以成江海,质变的前提需要量变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值