视频链接:
黑马程序员Spring注解开发教程,包含框架Spring+SpringMVC+SrpingTest+SpringData(事物)_哔哩哔哩_bilibili
1 目录层级 2 编写自定义beanName生成器CustomeBeanNameGenerator.java
package class05.config;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.Annotationmetadata;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import java.beans.Introspector;
import java.util.Map;
import java.util.Set;
public class CustomeBeanNameGenerator implements BeanNameGenerator {
private static final String COMPONENT_ANNOTATION_CLASSNAME = "org.springframework.stereotype.Component";
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
// 10.
String beanName = null;
// 1.判断当前bean的定义信息是否是注解的
if (beanDefinition instanceof AnnotatedBeanDefinition) {
// 2.把definition转成注解的bean定义信息
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
// 3.获取注解bean定义的元信息
Annotationmetadata annotationmetadata = annotatedBeanDefinition.getmetadata();
// 4.获取定义信息中的所有注解
Set types = annotationmetadata.getAnnotationTypes();
// 5.遍历types集合
for (String type : types) {
// 6.得到注解属性
//AnnotationAttributes attributes= AnnotationConfigUtils.attributesFor();
AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationmetadata.getAnnotationAttributes(type, false));
// 7.判断attributes是否为null,同事必须是@Component及其衍生注解(JSR250规范,JSR330规范)
if (attributes != null && this.isStereotypeWithNamevalue(type, annotationmetadata.getmetaAnnotationTypes(type), attributes)) {
Object value = attributes.get("value");
// 8.判断value的值是否为String类型
if (value instanceof String) {
String strVal = (String) value;
// 9.判断value属性是否有值,没有值的时候抛出一个异常,有值的时候strVal赋值给 beanName
if (StringUtils.hasLength(strVal)) {
if (beanName != null && !strVal.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent component names: '" + beanName + "' versus '" + strVal + "'");
}
beanName = strVal;
}
}
}
}
}
return beanName != null ? "myDefine_" + beanName : "myDefine_" + buildDefaultBeanName(beanDefinition);
}
private boolean isStereotypeWithNamevalue(String annotationType, Set metaAnnotationTypes, @Nullable Map attributes) {
boolean isStereotype = annotationType.equals("org.springframework.stereotype.Component") || metaAnnotationTypes.contains("org.springframework.stereotype.Component") || annotationType.equals("javax.annotation.ManagedBean") || annotationType.equals("javax.inject.Named");
return isStereotype && attributes != null && attributes.containsKey("value");
}
protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
return this.buildDefaultBeanName(definition);
}
protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
String shortClassName = ClassUtils.getShortName(beanClassName);
return Introspector.decapitalize(shortClassName);
}
}
SpringConfiguration.java
package class05.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "class05",nameGenerator = CustomeBeanNameGenerator.class)//扫描UserSerVice.java所在的包下的所有文件
public class SpringConfiguration {
//1.默认value/basePackageClasses 的情况下 被 @ComponentScan 修饰的类,它所处的包下的所有内容都会被扫描
//2.如果@ComponentScan指定了扫描的路径比如:“@ComponentScan(basePackageClasses = UserService.class)” 他就会扫描UserService.java所在的包下的文件,就不会再去扫描默认的被这个注解标注的类文件所处包下的所有文件。
}
AccountServiceImp1.java
package class05.service.AccountServiceImp;
import org.springframework.stereotype.Service;
import class05.service.AccountService;
//@Service
@Service("accountServiceImp2")
public class AccountServiceImp1 implements AccountService {
@Override
public void deleteAccount() {
System.out.println("删除用户2");
}
}
UserServiceImp1.java
package class05.service.UserServiceImp;
import org.springframework.stereotype.Service;
import class05.service.UserService;
@Service(value="userServiceImp3")
public class UserServiceImp1 implements UserService {
@Override
public void saveUser() {
System.out.println("保存用户3");
}
}
UserServiceImp2.java
package class05.service.UserServiceImp;
import org.springframework.stereotype.Service;
import class05.service.UserService;
@Service(value="userServiceImp4")
public class UserServiceImp2 implements UserService {
@Override
public void saveUser() {
System.out.println("保存用户4");
}
}
AccountService.java
package class05.service;
public interface AccountService {
public abstract void deleteAccount();
}
UserService.java
package class05.service;
public interface UserService {
public abstract void saveUser();
}
3 SpringComponentScanTest.java(测试类)
import class05.config.SpringConfiguration;
import class05.service.AccountService;
import class05.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringComponentScanTest {
public static void main(String[] args) {
//1.创建容器,基于注解创建方式。
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext("class05/config");
// 2.获取对象
UserService userService = ac.getBean("myDefine_userServiceImp3", UserService.class);
// 3.调用方法
userService.saveUser();
// 1.创建容器 传入被注解的类的字节码的方式
AnnotationConfigApplicationContext ac2 = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 2.获取对象
AccountService accountService = ac2.getBean("myDefine_accountServiceImp2", AccountService.class);
// 3.调用方法
accountService.deleteAccount();
}
}
4 debug运行查看控制台log
有 myDefine_xxxx 的beanName字样了,说明我定义的beanName生成器成功生效了。
"C:Program FilesJavajdk1.8.0_301binjava.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:61334,suspend=y,server=n -javaagent:C:UsersAdmin.IntelliJIdea2018.2systemcaptureAgentdebugger-agent.jar=file:/C:/Users/Admin/AppData/Local/Temp/capture.props -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_301jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_301jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_301jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_301jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_301jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_301jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_301jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_301jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_301jrelibextnashorn.jar;C:Program FilesJavajdk1.8.0_301jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_301jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_301jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_301jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_301jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_301jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_301jrelibjce.jar;C:Program FilesJavajdk1.8.0_301jrelibjfr.jar;C:Program FilesJavajdk1.8.0_301jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_301jrelibjsse.jar;C:Program FilesJavajdk1.8.0_301jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_301jrelibplugin.jar;C:Program FilesJavajdk1.8.0_301jrelibresources.jar;C:Program FilesJavajdk1.8.0_301jrelibrt.jar;C:UsersAdminDesktopAnnotationDemodemosdemo5targettest-classes;C:UsersAdminDesktopAnnotationDemodemosdemo5targetclasses;C:UsersAdmin.m2repositoryorgspringframeworkspring-context5.1.6.RELEASEspring-context-5.1.6.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-aop5.3.16spring-aop-5.3.16.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-beans5.3.16spring-beans-5.3.16.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-core5.3.16spring-core-5.3.16.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-jcl5.3.16spring-jcl-5.3.16.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-expression5.3.16spring-expression-5.3.16.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter2.6.4spring-boot-starter-2.6.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot2.6.4spring-boot-2.6.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-autoconfigure2.6.4spring-boot-autoconfigure-2.6.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter-logging2.6.4spring-boot-starter-logging-2.6.4.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-classic1.2.10logback-classic-1.2.10.jar;C:UsersAdmin.m2repositorychqoslogbacklogback-core1.2.10logback-core-1.2.10.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-to-slf4j2.17.1log4j-to-slf4j-2.17.1.jar;C:UsersAdmin.m2repositoryorgapachelogginglog4jlog4j-api2.17.1log4j-api-2.17.1.jar;C:UsersAdmin.m2repositoryorgslf4jjul-to-slf4j1.7.36jul-to-slf4j-1.7.36.jar;C:UsersAdmin.m2repositoryjakartaannotationjakarta.annotation-api1.3.5jakarta.annotation-api-1.3.5.jar;C:UsersAdmin.m2repositoryorgyamlsnakeyaml1.29snakeyaml-1.29.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-starter-test2.6.4spring-boot-starter-test-2.6.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-test2.6.4spring-boot-test-2.6.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkbootspring-boot-test-autoconfigure2.6.4spring-boot-test-autoconfigure-2.6.4.jar;C:UsersAdmin.m2repositorycomjaywayjsonpathjson-path2.6.0json-path-2.6.0.jar;C:UsersAdmin.m2repositorynetminidevjson-smart2.4.8json-smart-2.4.8.jar;C:UsersAdmin.m2repositorynetminidevaccessors-smart2.4.8accessors-smart-2.4.8.jar;C:UsersAdmin.m2repositoryorgow2asmasm9.1asm-9.1.jar;C:UsersAdmin.m2repositoryorgslf4jslf4j-api1.7.36slf4j-api-1.7.36.jar;C:UsersAdmin.m2repositoryjakartaxmlbindjakarta.xml.bind-api2.3.3jakarta.xml.bind-api-2.3.3.jar;C:UsersAdmin.m2repositoryjakartaactivationjakarta.activation-api1.2.2jakarta.activation-api-1.2.2.jar;C:UsersAdmin.m2repositoryorgassertjassertj-core3.21.0assertj-core-3.21.0.jar;C:UsersAdmin.m2repositoryorghamcresthamcrest2.2hamcrest-2.2.jar;C:UsersAdmin.m2repositoryorgjunitjupiterjunit-jupiter5.8.2junit-jupiter-5.8.2.jar;C:UsersAdmin.m2repositoryorgjunitjupiterjunit-jupiter-api5.8.2junit-jupiter-api-5.8.2.jar;C:UsersAdmin.m2repositoryorgopentest4jopentest4j1.2.0opentest4j-1.2.0.jar;C:UsersAdmin.m2repositoryorgjunitplatformjunit-platform-commons1.8.2junit-platform-commons-1.8.2.jar;C:UsersAdmin.m2repositoryorgapiguardianapiguardian-api1.1.2apiguardian-api-1.1.2.jar;C:UsersAdmin.m2repositoryorgjunitjupiterjunit-jupiter-params5.8.2junit-jupiter-params-5.8.2.jar;C:UsersAdmin.m2repositoryorgjunitjupiterjunit-jupiter-engine5.8.2junit-jupiter-engine-5.8.2.jar;C:UsersAdmin.m2repositoryorgjunitplatformjunit-platform-engine1.8.2junit-platform-engine-1.8.2.jar;C:UsersAdmin.m2repositoryorgmockitomockito-core4.0.0mockito-core-4.0.0.jar;C:UsersAdmin.m2repositorynetbytebuddybyte-buddy1.11.22byte-buddy-1.11.22.jar;C:UsersAdmin.m2repositorynetbytebuddybyte-buddy-agent1.11.22byte-buddy-agent-1.11.22.jar;C:UsersAdmin.m2repositoryorgobjenesisobjenesis3.2objenesis-3.2.jar;C:UsersAdmin.m2repositoryorgmockitomockito-junit-jupiter4.0.0mockito-junit-jupiter-4.0.0.jar;C:UsersAdmin.m2repositoryorgskyscreamerjsonassert1.5.0jsonassert-1.5.0.jar;C:UsersAdmin.m2repositorycomvaadinexternalgoogleandroid-json .0.20131108.vaadin1android-json-0.0.20131108.vaadin1.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-test5.3.16spring-test-5.3.16.jar;C:UsersAdmin.m2repositoryorgxmlunitxmlunit-core2.8.4xmlunit-core-2.8.4.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-jdbc5.1.6.RELEASEspring-jdbc-5.1.6.RELEASE.jar;C:UsersAdmin.m2repositoryorgspringframeworkspring-tx5.3.16spring-tx-5.3.16.jar;C:UsersAdmin.m2repositorymysqlmysql-connector-java5.1.45mysql-connector-java-5.1.45.jar;D:installtoolIntelliJ IDEA 2018.2.7libidea_rt.jar" SpringComponentScanTest Connected to the target VM, address: '127.0.0.1:61334', transport: 'socket' 16:13:07.949 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05configSpringConfiguration.class] 16:13:07.972 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7b49cea0 16:13:08.002 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' 16:13:08.059 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceAccountServiceImpAccountServiceImp1.class] 16:13:08.060 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceUserServiceImpUserServiceImp1.class] 16:13:08.060 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceUserServiceImpUserServiceImp2.class] 16:13:08.165 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor' 16:13:08.166 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory' 16:13:08.168 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' 16:13:08.169 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' 16:13:08.175 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'springConfiguration' 16:13:08.179 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_accountServiceImp2' 16:13:08.180 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_userServiceImp3' 16:13:08.180 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_userServiceImp4' 保存用户3 16:13:08.209 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7bbc8656 16:13:08.209 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' 16:13:08.214 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceAccountServiceImpAccountServiceImp1.class] 16:13:08.215 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceUserServiceImpUserServiceImp1.class] 16:13:08.215 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:UsersAdminDesktopAnnotationDemodemosdemo5targetclassesclass05serviceUserServiceImpUserServiceImp2.class] Disconnected from the target VM, address: '127.0.0.1:61334', transport: 'socket' 16:13:08.220 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor' 16:13:08.220 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory' 16:13:08.221 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' 16:13:08.222 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' 16:13:08.222 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'springConfiguration' 16:13:08.222 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_accountServiceImp2' 16:13:08.223 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_userServiceImp3' 16:13:08.223 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myDefine_userServiceImp4' 删除用户2 Process finished with exit code 0



