springboot⼏⼤注⼊注解⽅法的总结
最近在知乎上⾯看到⼀篇关于程序员⾯试的问题,⾯试官问我们⼀般有⼏种注⼊的⽅法,这⼏种注⼊的⽅法分别在什么时候运⽤⽐合理,当时我看到这个时候懵逼了,由于我⾃⼰也是刚刚接触springboot不久,所以就⾃⼰在平时运⽤的上⾯总结了⼀些知识点常⽤的⼏种springboot的注⼊⽅法,由于我是⼀个⼩萌新,所只要是能够起道注⼊的⽅法的注解我都列出来,有可能会有错,希望⼤家能够及时提出来我来解决:
1. @Autowired
2. @Resource
3. @Component
4. @Configuration
5. @Qualifie
6. @Bean
7. …
这⼏种常⽤的吗?难道还有什么其他的?当然有,下⾯我总结了⼀下⾃⼰对于这⼏种注⼊的看法和认识。
⾸先是我们使⽤频率较为⾼的@Autowired:
这个注解可能是我们使⽤频率较为频繁的⼀个注解的了,⼏乎在刚刚⼊门的时候,我们都会使⽤这个注释,那么@Autowired 注释的⼯作原理是什么呢?
第⼀:其实在启动spring IoC时,容器⾃动装载了⼀个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到
@Autowied、@Resource或@Inject时,就会在IoC容器⾃动查需要的bean,并装配给该对象的属性
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
第⼆:@Autowired 注释,它可以对类成员变量、⽅法及构造函数进⾏标注,完成⾃动装配的⼯作。 通过 @Autowired的使⽤来消除 set ,get⽅法。在使⽤@Autowired之前,我们对⼀个bean配置起属性时,是这⽤⽤的
<property name="属性名" value=" 属性值"/>
通过这种⽅式来,配置⽐较繁琐,⽽且代码⽐较多。在Spring 2.5 引⼊了 @Autowired 注释
我们平常直接引⽤的时候很少注意这些,只是⾃⼰写好了⼀个⽅法或者springboot⾃动配置好的⼀个⽅法我们要在另⼀个类中去调⽤,这个时候,我们就会采⽤该注释,例如:我已经写好⼀个⼯具类,此时,我需要在其他类中调⽤该⼯具类的⽅法:
/*
这是要被调⽤的类
*/
@Repository("userRepository")
public class UserRepositoryImps implements UserRepository{
@Override
public void save() {
System.out.println("UserRepositoryImps save is success");
}
}
已调⽤的类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pository.UserRepository;
/*
⽅法注⼊的类
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void save(){
userRepository.save();
}
}
接着我们开始聊⼀下@Resource这个注解:
第⼀:@Resource(这个注解属于J2EE的),默认按照名称进⾏装配,名称可以通过name属性进⾏指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进⾏安装名称查,如果注解写在setter⽅法上默认取属性名进⾏装配。当不到与名称匹配的bean时才按照类型进⾏装配。但是需要注意的是,如果name属性⼀旦指定,就只会按照名称进⾏装配。
第⼆:可以⽤在⽅法、属性、类上,通过CommonAnnotationBeanPostProcessor类实现依赖注⼊ 与
@AutoWired⼀致。但可以指定name属性来指定beanName,但如果name对应的bean不存在,则会抛出异常,且没有required属性。
当作⽤在类上⾯的时候:可以⽤来指定name
@Resource(name = "testMapper")
private TestMapper testMapper;
第三:@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false
@Autowired()
private StudentDao studentDao;
来,继续往下⾛,开始撸@Component这个注解:
第⼀:@Component泛指组件,当组件不好归类的时候,我们可以使⽤这个注解进⾏标注。
第⼆:@component (把普通pojo实例化到spring容器中,相当于配置⽂件中的<bean id="" class=""/
>)泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使⽤@Component来标注这个类。
例如下⾯的这个例⼦
注意:这个只能作⽤于类上⾯
package cn.scitc.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.Authentication;spring ioc注解
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component("myLoginSuccessHandler")
public class MyLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private Logger logger = Logger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletExceptio n, IOException {
response.setContentType("application/json;charset=UTF-8");
logger.info("登录成功");
PrintWriter out = Writer();
out.write(objectMapper.writeValueAsString("登录成功"));
out.flush();
out.close();
}
}
看了这么多,是不是有点累了,不⾏接着撸@Configuration的注解:
⾸先我们先明⽩从Spring3.0,@Configuration⽤于定义配置类,可替换xml配置⽂件,被注解的类内部包含有⼀个或多个被@Bean注解的⽅法,这些⽅法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进⾏扫描,并⽤于构建bean定义,初始化Spring容器。
在使⽤的时候需要注意:
1.@Configuration不可以是final类型;
2.@Configuration不可以是匿名类;
3.嵌套的configuration必须是静态类。
下⾯讲解详细的使⽤
第⼀:⽤@Configuration加载spring
1.1、@Configuration配置spring并启动spring容器
1.2、@Configuration启动容器+@Bean注册Bean
1.3、@Configuration启动容器+@Component注册Bean
1.4、使⽤ AnnotationConfigApplicationContext 注册 AppContext 类的两种⽅法
1.5、配置Web应⽤程序(l中配置AnnotationConfigApplicationContext)
第⼆:组合多个配置类
2.1、在@configuration中引⼊spring的xml配置⽂件
2.2、在@configuration中引⼊其它注解配置
2.3、@configuration嵌套(嵌套的Configuration必须是静态类)
2.4、@EnableXXX注解
2.5、@Profile逻辑组配置
2.6、使⽤外部变量
下⾯讲解⼀个⽐较常⽤的例⼦:不知道各位⼤佬的在⽤在SpringBoot 中使⽤Security安全框架的时候会出现⼀个默认的登录界⾯,但是我们⼀般不回去⽤哪个登录界⾯,这时候我们就应该⾃⼰去写⼀个登录的界⾯以及后端的实⾏⽅法,那么这个时候,@configuration就派上⽤场了,话不多说,直接上
例⼦:
package fig;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ErrorConfigurar {
/**
* ⾃定义错误页⾯
* @return
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return (factory -> {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/500");
ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN,"/403");
factory.addErrorPages(errorPage404);
factory.addErrorPages(errorPage403);
factory.addErrorPages(errorPage500);
});
}
}
注意:该注释也是⽤于全局的,所以定义在类上⾯。
接下来来⼀个就⽐较简单的@Qualifier了,这个注解在我认为就是@Autowired的⼩弟,它⼀般和@Autowired⼀起⽤,当 @Autowired()不带参数的时候@Qualifie就可以带上参数。Qualifier限定描述符除了能根据名字进⾏注⼊,更能进⾏更细粒度的控制如何选择候选者。
@Autowired()
@Qualifie("/studentDao")
private StudentDao studentDao;
现在继续撸⼀个叫@Bean的注解;
很多⼈就会问@Bean为什么可以当做注⼊来⽤呢?在刚刚开始的时候我也是认为@Bean就是封装⼀个POJO类⽽已,可是后⾯我觉得它是可以⽤来当做注⼊注解来使⽤的。
⾸先,@Bean可理解为⽤spring的时候xml⾥⾯的<bean>标签;
其次,@Bean是⼀个⽅法级别上的注解,主要⽤在@Configuration注解的类⾥,也可以⽤在@Component注解的类⾥,添加的bean的id 为⽅法名;
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
再接着:@bean 也可以依赖其他任意数量的bean,如果TransferService 依赖 AccountRepository,我们可以通过⽅法参数实现这个依赖;
@Bean
public TransferService transferService(AccountRepository accountRepository) {
return new TransferServiceImpl(accountRepository);
}
最后讲⼀下,指定bean的scope
使⽤@Scope注解来指定使⽤@Bean定义的bean
@Scope(“prototype”)
设置@Scope的属性proxyMode来指定,默认是ScopedProxyMode.NO, 你可以指定为默认是ScopedProxyMode.INTERFACES或者默认
是ScopedProxyMode.TARGET_CLASS。
@Bean
@SessionScope
public StuPreferences stuPreferences() {
return new StuPreferences();
}
@Bean
public Service StuService() {
StuService service = new SimpleStuService();
service.setStuPreferences(StuPreferences());
return service;
}
通过上⾯的说明,就⾜以说明这是可以⽤来注⼊的。
最后,我们来探讨⼀下private final修饰的变量可以被⽤来作为注⼊你们觉得可以吗?
试想,在⼀个⼤的项⽬中,⼏乎所有的引⽤都是⽤public、@Bean等相应的⽅法注⼊,那么就会造成代码的耦合度较⾼,造成了项⽬的维护困难,那么久只有被项⽬经理K⼀顿啦。
最后,由于我是⼩萌新⼀个,有总结不到位的,或者错误的,希望各位⼤佬指正出来。⼩弟感激不尽。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。