필기 springioc 주해 주입 대상 기본 구현
, , , , ,
, , , , ,
, , , ,
, , AOP , ,
Spring , , Spring ,
, , , AOP, AOP, AOP , ,
Spring , , , , , , AOP,
, , , Spring , , , ,
, , , copy , AOP
https://cloud.tencent.com/developer/article/1424714
( ): SpringIOC
https://www.jianshu.com/p/274275cf28ce
package com.learn.service;
//user
public interface UserService {
public void add();
public void del();
}
package com.learn.service.impl;
import org.springframework.transaction.annotation.Transactional;
import com.learn.annotation.ExtService;
import com.learn.service.UserService;
//user
/**
* @ExtService Spring
*
* @author Leon.Sun
*
*/
@ExtService
public class UserServiceImpl implements UserService {
@Transactional
public void add() {
System.out.println(" JAVA ....");
}
// ,
public void del() {
}
}
package com.learn.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Spring
/**
* service bean
* @author Leon.Sun
*
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtService {
}
package com.learn.utils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
*
*
*
*
*
*
* @author Leon.Sun
*
*/
public class ClassUtil {
/**
*
*/
public static List getAllClassByInterface(Class c) {
List returnClassList = null;
if (c.isInterface()) {
//
String packageName = c.getPackage().getName();
//
List> allClass = getClasses(packageName);
if (allClass != null) {
returnClassList = new ArrayList();
for (Class classes : allClass) {
//
if (c.isAssignableFrom(classes)) {
//
if (!c.equals(classes)) {
returnClassList.add(classes);
}
}
}
}
}
return returnClassList;
}
/*
*
*/
public static String[] getPackageAllClassName(String classLocation, String packageName) {
// packageName
String[] packagePathSplit = packageName.split("[.]");
String realClassLocation = classLocation;
int packageLength = packagePathSplit.length;
for (int i = 0; i < packageLength; i++) {
realClassLocation = realClassLocation + File.separator + packagePathSplit[i];
}
File packeageDir = new File(realClassLocation);
if (packeageDir.isDirectory()) {
String[] allClassName = packeageDir.list();
return allClassName;
}
return null;
}
/**
* package Class
*
* @param pack
* @return
*/
public static List> getClasses(String packageName) {
// class
List> classes = new ArrayList>();
//
boolean recursive = true;
//
String packageDirName = packageName.replace('.', '/');
// things
Enumeration dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
//
while (dirs.hasMoreElements()) {
//
URL url = dirs.nextElement();
//
String protocol = url.getProtocol();
//
if ("file".equals(protocol)) {
//
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
//
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// jar
// JarFile
JarFile jar;
try {
// jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// jar
Enumeration entries = jar.entries();
//
while (entries.hasMoreElements()) {
// jar jar META-INF
JarEntry entry = entries.nextElement();
String name = entry.getName();
// /
if (name.charAt(0) == '/') {
//
name = name.substring(1);
}
//
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// "/"
if (idx != -1) {
// "/" "."
packageName = name.substring(0, idx).replace('/', '.');
}
//
if ((idx != -1) || recursive) {
// .class
if (name.endsWith(".class") && !entry.isDirectory()) {
// ".class"
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
List> classes) {
// File
File dir = new File(packagePath);
//
if (!dir.exists() || !dir.isDirectory()) {
return;
}
//
File[] dirfiles = dir.listFiles(new FileFilter() {
// ( ) .class ( java )
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
//
for (File file : dirfiles) {
//
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// java .class
String className = file.getName().substring(0, file.getName().length() - 6);
try {
//
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
package com.learn.spring;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
import com.learn.annotation.ExtService;
import com.learn.utils.ClassUtil;
/**
* Spring IOC
* xml
*
*
*
* @author Leon.Sun
*
*/
public class ExtClassPathXmlApplicationContext {
//
private String packageName;
// bean
/**
* ConcurrentHashMap
* String bean id
* Object
* Class Object
*
*
*
* Object
*
*
*
*
* class
* new
* Class
* Spring
*
*
*
*
* ConcurrentHashMap
*
*
*
*
*
*
*
*
*
*
*
*
* null
*
*
*
*
*
*
*
*
*
*
*
* Spring bean
*
*/
private ConcurrentHashMap beans = null;
/**
*
*
* @param packageName
* @throws InstantiationException
* @throws IllegalAccessException
*/
public ExtClassPathXmlApplicationContext(String packageName) throws InstantiationException, IllegalAccessException {
/**
*
*/
this.packageName = packageName;
beans = new ConcurrentHashMap();
initBeans();
}
/**
*
*
*
*
*
* class
* com.learn.service
*
*
* API
*
*
*
* bean
*
*
*
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void initBeans() throws IllegalAccessException, InstantiationException {
//
/**
* packageName
* class
*
*
*
*
*/
List> classes = ClassUtil.getClasses(packageName);
// ExtService
findClassExistAnnotation(classes);
/**
* null
*
*
*
*
*
*
*/
if (beans == null || beans.isEmpty()) {
/**
*
*/
throw new RuntimeException(" ");
}
}
/**
* ExtService
*
*
*
* @param classes
* @throws InstantiationException
* @throws IllegalAccessException
*/
private void findClassExistAnnotation(List> classes) throws InstantiationException, IllegalAccessException {
/**
* classInfo
*
*/
for (Class> classInfo : classes) {
/**
*
* ExtService
*
*
*
*/
Annotation annotation = classInfo.getAnnotation(ExtService.class);
/**
*
*
* annotation null
*
*
*
*
*
*/
if (annotation != null) {
//
/**
*
*
*/
String className = classInfo.getName();
// Id
/**
*
* bean id
* beanid
* beanid
* beanid
* beanid
*
*
*
*
* beanid
* beanid
*
*
*
*
* classInfo.getSimpleName()
*
* className
*
*
*
*
*
*
*
*
*
*
* continue
* break
*
* continue
*
*
*
* bean
*
*
*
*/
beans.put(toLowerCaseFirestOne(classInfo.getSimpleName()), newInstance(classInfo));
}
}
}
/** */
/**
*
*
* newClassName
* name
* beanid
*
* @param className
* @return
*/
private String toLowerCaseFirestOne(String className) {
return new StringBuilder().append(Character.toLowerCase(className.charAt(0))).append(className.substring(1)).toString();
}
/** Bean */
/**
* beanId
*
*
* @param beanId
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public Object getBean(String beanId) throws IllegalAccessException, InstantiationException {
/**
* beanid
*
* beanid
*
*
*/
if (StringUtils.isEmpty(beanId)) {
/**
* beanid
* beanid
*
*
*/
throw new RuntimeException("BeanID ");
}
/**
* beanid
*
* Spring bean
*
*/
return beans.get(beanId);
}
/** Bean*/
private Object newInstance(Class> classInfo) throws IllegalAccessException, InstantiationException {
/**
*
*
* bean
*
*
*/
if (classInfo == null) {
throw new RuntimeException(" ID bean");
}
/**
*
*
*
*
*/
return classInfo.newInstance();
}
/** */
private void attrAssign(Class> classInfo) {
//
Field[] fields = classInfo.getFields();
//
for (Field field : fields) {
ExtService extService = field.getAnnotation(ExtService.class);
if (extService != null) {
//
String fieldName = field.getName();
}
}
}
}
package com.learn;
import com.learn.service.UserService;
import com.learn.spring.ExtClassPathXmlApplicationContext;
/**
*
*
*
*
*
*
*
* @author Leon.Sun
*
*/
public class Test001 {
public static void main(String[] args) throws Exception {
/**
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* JAVA
*
*
*
*
*
*
*/
/**
*
*
* bean
*
*
*/
/**
*
*
* JAVA
*
*
*
*
*
* AOP
* AOP
* AOP
* AOP AOP
*
*
*
*
*
*/
/**
*
* com.learn.service.impl
* Service @ExtService
* UserServiceImpl
*
* UserServiceImpl
*
*
*/
ExtClassPathXmlApplicationContext app = new ExtClassPathXmlApplicationContext("com.learn.service.impl");
UserService userService = (UserService) app.getBean("userServiceImpl");
/**
*
*/
System.out.println(userService);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.