開發顛覆者SpringBoot實戰---------Spring的基礎學習

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>myspringboot</groupId>
  <artifactId>spring4</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- java編譯級別 -->
  <properties>
    <java.version>1.7</java.version>
  </properties>
  <dependencies>
    <!-- spring容器(bean) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <!-- spring aop支持和aspectj依賴 -->
    <!-- Aspectj是aop的java實現方案,AspectJ是一種編譯期的用註解形式實現的AOP -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.5</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.5</version>
    </dependency>
    <!-- 增加commons-io可簡化文件相關操作 -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.3</version>
    </dependency>
    <!-- 增加JSR250支持,這是註解 -->
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>jsr250-api</artifactId>
        <version>1.0</version>
    </dependency>
    <!-- Spring test支持 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
  </dependencies>
  <!-- maven編譯級別 -->
  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

一、依賴注入(bean)

/**
 * 功能類的bean
 * @author think
 */
@Service
public class FunctionService {
    public String sayHello(String str){
        return "hello " + str + "!";
    }
}

/**
 * 使用功能類的bean
 * @author think
 */
@Service
public class UseFunctionService {
    @Autowired
    private FunctionService service;
    public String sayHello(String str){
        return service.sayHello(str);
    }
}

/**
 * 配置
 * @author think
 */
@Configuration//聲明註解類
@ComponentScan("com.CreateBeanTest.service")//掃描的包
public class DiConfig {
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);
        UseFunctionService service = context.getBean(UseFunctionService.class);
        System.out.println(service.sayHello("spring學習"));
        context.close();
    }
}

二、AOP

/**
 * 自定義註解類
 * @author think
 */
@Target(ElementType.METHOD)//註解使用範圍,使用在方法上
@Retention(RetentionPolicy.RUNTIME)//註解將保留到運行時
@Documented//表明這個註解應該被 javadoc工具記錄,會被包括在生成的文檔
public @interface Action {
    String name();
}

/**
 * 切面類
 * @author think
 */
@Aspect//聲明這是切面
@Component//讓切面成爲spring容器管理的bean
public class LogAspect {
    @Pointcut("@annotation(com.AopTest.aspect.Action)")//聲明切點
    public void annotationPointCut(){}
    @After("annotationPointCut()")
    public void after(JoinPoint point){
        MethodSignature sign = (MethodSignature) point.getSignature();
        Method method = sign.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("註解式攔截:" + action.name());
    }
    @Before("execution(* com.AopTest.service.*.*(..))")
    public void before(JoinPoint point){
        MethodSignature sign = (MethodSignature) point.getSignature();
        Method method = sign.getMethod();
        System.out.println("方法規則式式攔截:" + method.getName());
    }
}

/**
 * 使用註解的被攔截類
 * @author think
 */
@Service
public class AnnotationService {
    @Action(name = "註解式攔截")
    public void add(){}
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.AopTest")
@EnableAspectJAutoProxy//開啓spring對aspectj代理的支持
public class AopConfig {
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        AnnotationService service = context.getBean(AnnotationService.class);
        service.add();
        context.close();
    }
}

三、scope

/**
 * prototype的bean
 * @author think
 */
@Service
@Scope("prototype")
public class PrototypeService {
}

/**
 * singleton的bean
 * @author think
 */
@Service
@Scope("singleton")//默認不需要寫
public class SingletonService {
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ScopeTest.service")
public class ScopeConfig {
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        SingletonService singletonService1 = context.getBean(SingletonService.class);
        SingletonService singletonService2 = context.getBean(SingletonService.class);
        PrototypeService prototypeService1 = context.getBean(PrototypeService.class);
        PrototypeService prototypeService2 = context.getBean(PrototypeService.class);
        System.out.println(singletonService1);
        System.out.println(singletonService2);
        System.out.println(prototypeService1);
        System.out.println(prototypeService2);
        context.close();
    }
}

四、El和資源調用

需要生成兩個文件test.txt和text.properties

/**
 * 一個測試service,用來獲取類的屬性
 * @author think
 */
@Service
public class TestService {
    @Value("其他類的屬性")
    private String otherString;
    public String getOtherString() {
        return otherString;
    }
    public void setOtherString(String otherString) {
        this.otherString = otherString;
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ElTest")
@PropertySource("classpath:com/ElTest/test.properties")//指定文件地址
public class ElConfig {
    @Value("i love you")//注入普通字符串
    private String normal;
    @Value("#{systemProperties['os.name']}")//注入系統屬性
    private String osName;
    @Value("#{testService.otherString}")//注入其他bean屬性
    private String otherString;
    @Value("#{T(java.lang.Math).random()*100.0}")//注入表達式結果
    private String randomNumber;
    @Value("classpath:com/ElTest/test.txt")//注入文件資源
    private Resource testFile;
    @Value("http://www.baidu.com")//注入網站資源
    private Resource testUrl;
    @Value("${author.name}")//注入配置文件
    private String authorName;
    @Autowired
    private Environment environment;//注入系統環境變量
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        return new PropertySourcesPlaceholderConfigurer();
    }
    public void outputResource() throws IOException{
        System.out.println(normal);
        System.out.println(osName);
        System.out.println(otherString);
        System.out.println(randomNumber);
        System.out.println(IOUtils.toString(testFile.getInputStream()));
        System.out.println(IOUtils.toString(testUrl.getInputStream()));
        System.out.println(authorName);
        System.out.println(environment.getProperty("author.sex"));
    }
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig config = context.getBean(ElConfig.class);
        config.outputResource();
        context.close();
    }
}

五、bean的創建和銷燬

/**
 * 傳統的bean形式,使用initMethod和destroyMethod
 * @author think
 */
public class BeanService {
    public void init(){
        System.out.println("bean創建");
    }
    public BeanService(){
        System.out.println("BeanService構造函數初始化");
    }
    public void destory(){
        System.out.println("bean銷燬");
    }
}

/**
 * 使用JSR250註解來創建和銷燬
 * @author think
 */
public class JSR250Service {
    @PostConstruct//在構造函數執行完後執行
    public void init(){
        System.out.println("jsr250創建");
    }
    public JSR250Service(){
        System.out.println("JSR250Service構造函數初始化");
    }
    @PreDestroy//在bean銷燬之前執行
    public void destory(){
        System.out.println("jsr250銷燬");
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.InitAndDstoryBeanTest")
public class PrePostConfig {
    @Bean(initMethod="init",destroyMethod="destory")
    public BeanService beanService(){
        return new BeanService();
    }
    @Bean
    public JSR250Service jsr250Service(){
        return new JSR250Service();
    }
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);
        BeanService beanService = context.getBean(BeanService.class);
        JSR250Service jsr250Service = context.getBean(JSR250Service.class);
        context.close();
    }
}

六、時間event

/**
 * 自定義事件
 * @author think
 */
public class Event extends ApplicationEvent{
    private String msg;
    public Event(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

/**
 * 事件監聽器
 * @author think
 */
@Component
public class Listener implements ApplicationListener<Event>{
    @Override
    public void onApplicationEvent(Event event) {
        String msg = event.getMsg();
        System.out.println("接收到msg :" + msg);
    }
}

/**
 * 事件發佈
 * @author think
 */
@Component
public class Publisher {
    @Autowired
    public ApplicationContext context;
    public void publish(String msg){
        context.publishEvent(new Event(this, msg));
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.EventTest")
public class EventConfig {
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
        Publisher publisher = context.getBean(Publisher.class);
        publisher.publish("哈哈");
        context.close();
    }
}

七、Scheduled計劃任務

/**
 * 執行計劃任務類
 * @author think
 */
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate = 5000)//間隔時間執行
    public void reportCurrentTime(){
        System.out.println("每五秒執行:" + format.format(new Date()));
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ScheduledTest")
@EnableScheduling//開啓對計劃任務的支持
public class ScheduledConfig {
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduledConfig.class);
    }
}

八、多線程

/**
 * 任務執行類
 * @author think
 */
@Service
public class AsynTaskService {
    @Async//表明這是一個異步方法,會被自動注入taskExecutor
    public void executeAsyncTask(Integer i){
        System.out.println("執行異步任務:" + i);
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.TaskExecutorTest")
@EnableAsync//開啓異步任務支持
public class TaskExecutorConfig implements AsyncConfigurer{
    @Override
    public Executor getAsyncExecutor() {//獲得一個基於線程池的teskExecutor
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

/**
 * 執行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsynTaskService asynTaskService = context.getBean(AsynTaskService.class);
        for (int i = 0; i < 10; i++) {
            asynTaskService.executeAsyncTask(i);
        }
        context.close();
    }
}

附:@Enable註解的使用*

  • @EnableAspectJAutoProxy ———- 開啓spring對aspectj代理的支持
  • @EnableScheduling ———- 開啓對計劃任務的支持
  • @EnableAsync ———- 開啓異步任務支持
  • @EnableWebMvc ———- 開啓web mvc的配置支持
  • @EnableConfigurationProperties ———- 配置bean的支持
  • @EnableJpaRepositories ———- Spring Data Jpa的支持
  • @EnableTransactionManagement ———- 註解式事務的支持
  • @EnableCaching ———- 開啓緩存支持
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章