languages.md 172.2 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333
# 语言支持

## 1. Kotlin

[Kotlin](https://kotlinlang.org)是一种以 JVM(和其他平台)为目标的静态类型语言,它允许编写简洁和优雅的代码,同时使用用 Java 编写的现有库提供非常好的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)

Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序,就好像 Spring 框架是一个原生 Kotlin 框架一样。除了 Java 之外,参考文档的大多数代码示例都是在 Kotlin 中提供的。

用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring 引导和它的[dedicated Kotlin support](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-kotlin.html)[这个全面的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)将教你如何使用[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)用 Kotlin 构建 Spring 引导应用程序。

如果你需要支持,可以随时加入[Kotlin Slack](https://slack.kotlinlang.org/)的 # Spring 通道,或者使用`spring``kotlin`作为标记在[Stackoverflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上提问。

### 1.1.所需经费

Spring 框架支持 Kotlin 1.3+,并且需要[`kotlin-stdlib`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib)(或其变体之一,例如[`kotlin-stdlib-jdk8`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8))和[`kotlin-reflect`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-reflect)才能在 Classpath 上存在。如果你在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上引导一个 Kotlin 项目,则默认情况下会提供它们。

|   |对于使用 Jackson 对 Kotlin 类的 JSON 数据进行序列化或反序列化,需要[Jackson Kotlin module](https://github.com/FasterXML/jackson-module-kotlin)<br/>,因此,如果你有此需要,请确保将 `com.fasterxml.Jackson.module:Jackson-module- Kotlin `dependency 添加到你的项目中。<br/>在 Classpath 中找到时,它会自动注册。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.2.扩展

Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html)提供了扩展具有附加功能的现有类的能力。 Spring 框架 Kotlin API 使用这些扩展来向现有 Spring API 添加新的 Kotlin 特定的便利。

[Spring 框架 KDoc API](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/)列表和文档都是可用的 Kotlin 扩展和 DSL。

|   |请记住, Kotlin 扩展需要导入才能使用。这意味着,<br/>例如,`GenericApplicationContext.registerBean` Kotlin 扩展<br/>只有当`org.springframework.context.support.registerBean`被导入时才可用。<br/>也就是说,与静态导入类似,IDE 在大多数情况下应该自动建议导入。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

例如,[Kotlin reified type parameters](https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)为 JVM[泛型擦除](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)提供了一种变通方法,而 Spring 框架提供了一些扩展来利用这一特性。这允许更好的 Kotlin API`RestTemplate`、 Spring WebFlux 中的新`WebClient`以及其他各种 API。

|   |其他库,例如 Reactor 和 Spring Data,也为它们的 API 提供了 Kotlin 扩展,因此总体上提供了更好的 Kotlin 开发体验。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------|

要在 Java 中检索`User`对象的列表,通常需要编写以下内容:

```
Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
```

对于 Kotlin 和 Spring 框架扩展,你可以改为编写以下内容:

```
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
```

正如在 Java 中一样, Kotlin 中的`users`是强类型的,但是 Kotlin 聪明的类型推断允许更短的语法。

### 1.3.零安全

Kotlin 的关键特性之一是[null-safety](https://kotlinlang.org/docs/reference/null-safety.html),它在编译时干净地处理`null`值,而不是在运行时遇到著名的 `nullPointerexception’。这使得应用程序通过可否定性声明和表达“值或无值”语义而更安全,而不需要支付包装器的费用,例如`Optional`。( Kotlin 允许使用具有可空的值的函数结构。参见[comprehensive guide to Kotlin null-safety](https://www.baeldung.com/kotlin-null-safety)。)

虽然 Java 不允许在其类型系统中表示空安全,但 Spring 框架通过在`org.springframework.lang`包中声明的对工具友好的注释提供了[null-safety of the whole Spring Framework API](core.html#null-safety)。默认情况下,来自 Kotlin 中使用的 Java API 的类型被识别为[platform types](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types),对此可以放松空值检查。[Kotlin support for JSR-305 annotations](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)和 Spring 空值注释为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,并具有在编译时处理`null`相关问题的优点。

|   |诸如 Reactor 或 Spring Data 之类的库提供了空安全的 API 来利用此功能。|
|---|-----------------------------------------------------------------------------------------|

你可以通过添加`-Xjsr305`编译器标志和以下选项来配置 JSR-305 检查:`-Xjsr305={strict|warn|ignore}`。

对于 Kotlin 版本 1.1+,默认行为与`-Xjsr305=warn`相同。在从 Spring API 推断出的 Kotlin 类型中,`strict`值需要将 Spring FrameworkAPI 的空安全性考虑在内,但在使用该值时,应该知道 Spring API 的零性声明即使在较小的版本之间也可以发展,并且将来可能会添加更多的检查。

|   |目前还不支持泛型类型参数、varargs 和数组元素的可空性,<br/>,但应该在即将发布的版本中支持。有关最新信息,请参见[this discussion](https://github.com/Kotlin/KEEP/issues/79)。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.4.类和接口

Spring 框架支持各种 Kotlin 构造,例如通过主构造函数实例化 Kotlin 类、不可变类数据绑定和具有默认值的函数可选参数。

Kotlin 通过专用的`KotlinReflectionParameterNameDiscoverer`来识别参数名称,该参数名称允许查找接口方法参数名称,而不需要在编译过程中启用 Java8`-parameters`编译器标志。

你可以将配置类声明为[顶层或嵌套的,但不是内部的](https://kotlinlang.org/docs/reference/nested-classes.html),因为后者需要对外部类的引用。

### 1.5.注解

Spring 框架还利用[Kotlin null-safety](https://kotlinlang.org/docs/reference/null-safety.html)来确定是否需要 HTTP 参数,而无需显式地定义`required`属性。这意味着`@RequestParam name: String?`被视为不需要,相反,`@RequestParam name: String`被视为需要。 Spring 消息传递`@Header`注释上也支持此功能。

以类似的方式, Spring  Bean 带有`@Autowired`、`@Bean`或`@Inject`的注入使用该信息来确定是否需要 Bean。

例如,`@Autowired lateinit var thing: Thing`意味着必须在应用程序上下文中注册类型`Thing`的 Bean,而`@Autowired lateinit var thing: Thing?`如果不存在这样的 Bean,则不会引发错误。

遵循相同的原则,`@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)`意味着类型`Toy`的 Bean 必须在应用程序上下文中注册,而类型`Car`的 Bean 可能存在,也可能不存在。同样的行为也适用于自动连线构造函数参数。

|   |如果在具有属性或主构造函数<br/>参数的类上使用 Bean 验证,则可能需要使用[注释使用-站点目标](https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets),<br/>,例如`@field:NotNull`或`@get:Size(min=5, max=15)`,如[这个堆栈溢出响应](https://stackoverflow.com/a/35853200/1092077)中所述。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.6. Bean 定义 DSL

Spring Framework 支持通过使用 lambdas 作为 XML 或 Java 配置的替代方案(`@configuration` 和`@Bean`)以功能方式注册 bean。简而言之,它允许你用 lambda 注册 bean,lambda 充当`FactoryBean`。这种机制非常有效,因为它不需要任何反射或 CGlib 代理。

例如,在 Java 中,你可以编写以下内容:

```
class Foo {}

class Bar {
    private final Foo foo;
    public Bar(Foo foo) {
        this.foo = foo;
    }
}

GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Foo.class);
context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class)));
```

在 Kotlin 中,使用具体化的类型参数和`GenericApplicationContext` Kotlin 扩展,你可以改为编写以下内容:

```
class Foo

class Bar(private val foo: Foo)

val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean { Bar(it.getBean()) }
}
```

当类`Bar`只有一个构造函数时,你甚至可以只指定 Bean 类,构造函数参数将根据类型自动连线:

```
val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean<Bar>()
}
```

为了允许更多的声明性方法和更干净的语法, Spring Framework 提供了[Kotlin bean definition DSL](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/)它通过一个干净的声明性 API 声明`ApplicationContextInitializer`,它允许你处理配置文件和`Environment`,以自定义如何注册 bean。

在下面的示例中,请注意:

* 类型推理通常允许避免为 Bean 引用指定类型,如`ref("bazBean")`

* 在本例中,可以使用 Kotlin 顶级函数使用`bean(::myRouter)`之类的可调用引用来声明 bean。

* 当指定`bean<Bar>()`或`bean(::myRouter)`时,参数将按类型自动连线。

* 只有在`foobar`配置文件处于活动状态时,才会注册`FooBar` Bean

```
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)

val myBeans = beans {
    bean<Foo>()
    bean<Bar>()
    bean("bazBean") {
        Baz().apply {
            message = "Hello world"
        }
    }
    profile("foobar") {
        bean { FooBar(ref("bazBean")) }
    }
    bean(::myRouter)
}

fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router {
    // ...
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|

然后,你可以使用这个`beans()`函数在应用程序上下文中注册 bean,如下例所示:

```
val context = GenericApplicationContext().apply {
    myBeans.initialize(this)
    refresh()
}
```

|   |Spring boot 是基于 javaconfig 和[does not yet provide specific support for functional bean definition](https://github.com/spring-projects/spring-boot/issues/8115),<br/>,但可以通过 Spring boot 的`ApplicationContextInitializer`支持实验性地使用函数 Bean 定义。<br/>查看[这个堆栈溢出回答](https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685)以获得更多详细信息和最新信息。另见[Spring Fu incubator](https://github.com/spring-projects/spring-fu)中开发的实验 Kofu DSL。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.7.万维网

#### 1.7.1.路由器 DSL

Spring Framework 自带的路由器 DSL 有 3 种类型:

* WebMVC.FNDSL with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.servlet.function/router.html)

* webflux.FN[Reactive](web-reactive.html#webflux-fn)dsl with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/router.html)

* webflux.FN[Coroutines](#coroutines)dsl with[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)

这些 DSL 允许你编写干净且惯用的 Kotlin 代码来构建`RouterFunction`实例,如下例所示:

```
@Configuration
class RouterRouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = router {
        accept(TEXT_HTML).nest {
            GET("/") { ok().render("index") }
            GET("/sse") { ok().render("sse") }
            GET("/users", userHandler::findAllView)
        }
        "/api".nest {
            accept(APPLICATION_JSON).nest {
                GET("/users", userHandler::findAll)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::stream)
            }
        }
        resources("/**", ClassPathResource("static/"))
    }
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。当你需要根据动态数据(例如,来自数据库)注册路由时,这可能是有用的<br/>。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

具体例子见[MiXiT project](https://github.com/mixitconf/mixit/)。

#### 1.7.2.MockMVC DSL

Kotlin DSL 通过 Kotlin 扩展提供,以便提供更惯用的 Kotlin API 并允许更好的可发现性(不使用静态方法)。

```
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
    secure = true
    accept = APPLICATION_JSON
    headers {
        contentLanguage = Locale.FRANCE
    }
    principal = Principal { "foo" }
}.andExpect {
    status { isOk }
    content { contentType(APPLICATION_JSON) }
    jsonPath("$.name") { value("Lee") }
    content { json("""{"someBoolean": false}""", false) }
}.andDo {
    print()
}
```

#### 1.7.3. Kotlin 脚本模板

Spring Framework 提供了一个[“ScriptemplateView”](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/script/ScriptTemplateView.html),它支持[JSR-223](https://www.jcp.org/en/jsr/detail?id=223)通过使用脚本引擎来呈现模板。

通过利用`scripting-jsr223`依赖关系,可以使用这样的特性来呈现带有[kotlinx.html](https://github.com/Kotlin/kotlinx.html)DSL 或 Kotlin 多行插值`String`的基于 Kotlin 的模板。

`build.gradle.kts`

```
dependencies {
        runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
```

配置通常使用`ScriptTemplateConfigurer`和`ScriptTemplateViewResolver`bean。

`KotlinScriptConfiguration.kt`

```
@Configuration
class KotlinScriptConfiguration {

    @Bean
    fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
        engineName = "kotlin"
        setScripts("scripts/render.kts")
        renderFunction = "render"
        isSharedEngine = false
    }

    @Bean
    fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
        setPrefix("templates/")
        setSuffix(".kts")
    }
}
```

有关更多详细信息,请参见[kotlin-script-templating](https://github.com/sdeleuze/kotlin-script-templating)示例项目。

#### 1.7.4. Kotlin 多平台序列化

在 Spring Framework5.3 中,[Kotlin multiplatform serialization](https://github.com/Kotlin/kotlinx.serialization)在 Spring MVC、 Spring WebFlux 和 Spring Messaging 中得到了支持。内置支持目前只针对 JSON 格式。

要启用它,请按照[那些指示](https://github.com/Kotlin/kotlinx.serialization#setup)添加相关的依赖项和插件。对于 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 Classpath 中,那么它们将默认地被配置,因为 Kotlin 序列化被设计为仅序列化 Kotlin 用`@Serializable`注释的类。使用 Spring 消息传递,如果你想要自动配置,则确保 Jackson、GSON 或 JSONB 都不在 Classpath 中,如果需要配置 Jackson,则手动配置`KotlinSerializationJsonMessageConverter`。

### 1.8.协理

Kotlin [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)是 Kotlin 轻量级线程,允许以强制方式编写非阻塞代码。在语言端,挂起函数为异步操作提供了抽象,而在库端[Kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)提供了[`async { }`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html)之类的函数和[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)之类的类型。

Spring 框架在以下范围上为协程提供支持:

* [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)和[Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)返回 Spring MVC 和 WebFlux 中支持的值,注释`@Controller`

* Spring MVC 和 WebFlux 注释`@Controller`中的挂起功能支持

* WebFlux[client](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.client/index.html)和[server](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/index.html)函数 API 的扩展。

* WebFlux.FN[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL

* 挂起函数和`Flow`在 RSocket 中支持`@MessageMapping`注释方法

* [rsocketrequester’](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.messaging.rsocket/index.html)的扩展

#### 1.8.1.依赖关系

当`kotlinx-coroutines-core`和`kotlinx-coroutines-reactor`依赖项位于 Classpath 中时,将启用协程支持:

`build.gradle.kts`

```
dependencies {

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}")
}
```

支持`1.4.0`及以上版本。

#### 1.8.2.反应性如何转化为协程?

对于返回值,从 Active 到 CoroutineAPI 的转换如下:

* `fun handler(): Mono<Void>`变为`suspend fun handler()`

* `fun handler(): Mono<T>`变为`suspend fun handler(): T`或`suspend fun handler(): T?`取决于`Mono`是否为空(具有更静态类型的优点)

* `fun handler(): Flux<T>`变为`fun handler(): Flow<T>`

输入参数:

* 如果不需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(value: T)`,因为可以调用挂起的函数来获得值参数。

* 如果需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(supplier: suspend () → T)`或`fun handler(supplier: suspend () → T?)`

[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在协程世界中是`Flux`等价的,适用于冷热气流、有限气流或无限气流,有以下主要区别:

* `Flow`是推拉式的,而`Flux`是推拉式的混合动力

* 背压是通过悬挂功能实现的。

* `Flow`只有一个[single suspending `collect` method](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html),运算符实现为[extensions](https://kotlinlang.org/docs/reference/extensions.html)

* [运营商很容易实现。](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common/src/flow/operators)感谢协程

* 扩展允许将自定义运算符添加到`Flow`

* 收集操作是挂起的功能

* [`map` operator](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html)支持异步操作(不需要`flatMap`),因为它需要一个挂起的函数参数

阅读这篇关于[Going Reactive with Spring, Coroutines and Kotlin Flow](https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow)的博客文章,了解更多详细信息,包括如何与协程同时运行代码。

#### 1.8.3.控制器

下面是一个协程`@RestController`的例子。

```
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {

    @GetMapping("/suspend")
    suspend fun suspendingEndpoint(): Banner {
        delay(10)
        return banner
    }

    @GetMapping("/flow")
    fun flowEndpoint() = flow {
        delay(10)
        emit(banner)
        delay(10)
        emit(banner)
    }

    @GetMapping("/deferred")
    fun deferredEndpoint() = GlobalScope.async {
        delay(10)
        banner
    }

    @GetMapping("/sequential")
    suspend fun sequential(): List<Banner> {
        val banner1 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        val banner2 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        return listOf(banner1, banner2)
    }

    @GetMapping("/parallel")
    suspend fun parallel(): List<Banner> = coroutineScope {
        val deferredBanner1: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        val deferredBanner2: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        listOf(deferredBanner1.await(), deferredBanner2.await())
    }

    @GetMapping("/error")
    suspend fun error() {
        throw IllegalStateException()
    }

    @GetMapping("/cancel")
    suspend fun cancel() {
        throw CancellationException()
    }

}
```

还支持`@Controller`的视图呈现。

```
@Controller
class CoroutinesViewController(banner: Banner) {

    @GetMapping("/")
    suspend fun render(model: Model): String {
        delay(10)
        model["banner"] = banner
        return "index"
    }
}
```

#### 1.8.4.WebFlux.FN

下面是通过[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL 和相关处理程序定义的协程路由器的示例。

```
@Configuration
class RouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = coRouter {
        GET("/", userHandler::listView)
        GET("/api/user", userHandler::listApi)
    }
}
```

```
class UserHandler(builder: WebClient.Builder) {

    private val client = builder.baseUrl("...").build()

    suspend fun listView(request: ServerRequest): ServerResponse =
            ServerResponse.ok().renderAndAwait("users", mapOf("users" to
            client.get().uri("...").awaitExchange().awaitBody<User>()))

    suspend fun listApi(request: ServerRequest): ServerResponse =
                ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
                client.get().uri("...").awaitExchange().awaitBody<User>())
}
```

#### 1.8.5.交易

通过 Spring 框架 5.2 提供的反应式事务管理的编程变体,支持协程上的事务。

对于挂起的函数,提供了`TransactionalOperator.executeAndAwait`扩展。

```
import org.springframework.transaction.reactive.executeAndAwait

class PersonRepository(private val operator: TransactionalOperator) {

    suspend fun initDatabase() = operator.executeAndAwait {
        insertPerson1()
        insertPerson2()
    }

    private suspend fun insertPerson1() {
        // INSERT SQL statement
    }

    private suspend fun insertPerson2() {
        // INSERT SQL statement
    }
}
```

对于 Kotlin `Flow`,提供了一个`Flow<T>.transactional`扩展。

```
import org.springframework.transaction.reactive.transactional

class PersonRepository(private val operator: TransactionalOperator) {

    fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)

    private fun findPeople(): Flow<Person> {
        // SELECT SQL statement
    }

    private suspend fun updatePerson(person: Person): Person {
        // UPDATE SQL statement
    }
}
```

### 1.9. Spring  Kotlin 中的项目

本节提供了一些值得在 Kotlin 中开发 Spring 项目的具体提示和建议。

#### 1.9.1.默认情况下为 final

默认情况下,[all classes in Kotlin are `final`](https://discuss.kotlinlang.org/t/classes-final-by-default/166)。类上的`open`修饰符与 Java 的`final`相反:它允许其他人继承这个类。这也适用于成员函数,因为它们需要标记为`open`才能被重写。

虽然 Kotlin 的 JVM 友好设计通常与 Spring 无摩擦,但如果不考虑这一事实,则此特定的 Kotlin 特性可以阻止应用程序启动。这是因为 Spring bean(例如`@Configuration`注释类,由于技术原因,默认情况下需要在运行时进行扩展)通常是由 CGLIB 代理的。解决方法是在 Spring bean 的每个类和成员函数上添加一个`open`关键字,这些类和成员函数是由 CGlib 代理的,这可能很快会变得很痛苦,并且违反 Kotlin 保持代码简洁和可预测的原则。

|   |也可以通过使用`@Configuration(proxyBeanMethods = false)`来避免配置类的 CGLIB 代理。<br/>查看[“ProxyBeanMethods”Javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html#proxyBeanMethods--)以获得更多详细信息。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

幸运的是, Kotlin 提供了一个[`kotlin-spring`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin)插件(`kotlin-allopen`插件的预先配置版本),该插件自动为使用以下注释之一进行注释或元注释的类型打开类及其成员函数:

* `@Component`

* `@Async`

* `@Transactional`

* `@Cacheable`

元注释支持意味着使用`@Configuration`、`@Controller`、<restcontroller`、或`@Repository`进行注释的类型将自动打开,因为这些注释是用`@Component`进行元注释的。

[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)默认情况下启用`kotlin-spring`插件。因此,在实践中,你可以在不添加任何`open`关键字的情况下编写 Kotlin bean,就像在 Java 中一样。

|   |Spring 框架文档中的 Kotlin 代码示例并未在类及其成员函数上明确指定“open”。示例是使用`kotlin-allopen`插件为<br/>项目编写的,因为这是最常用的设置。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.2.使用不可变类实例实现持久性

在 Kotlin 中,在主构造函数中声明只读属性是很方便的,并且被认为是一种最佳实践,如下例所示:

```
class Person(val name: String, val age: Int)
```

你可以选择添加[the `data` keyword](https://kotlinlang.org/docs/reference/data-classes.html),以使编译器自动从主构造函数中声明的所有属性派生出以下成员:

* `equals()``hashCode()`

* `toString()`的形式`"User(name=John, age=42)"`

* `componentN()`与其声明顺序中的属性对应的函数

* `copy()`函数

正如下面的示例所示,这允许对单个属性进行简单的更改,即使`Person`属性是只读的:

```
data class Person(val name: String, val age: Int)

val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
```

常见的持久性技术(例如 JPA)需要一个默认的构造函数,从而阻止了这种设计。幸运的是,对于这个[“默认构造函数地狱”](https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell)有一种解决方法,因为 Kotlin 提供了一个[`kotlin-jpa`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-jpa-compiler-plugin)插件,该插件为带有 JPA 注释的类生成合成的无 arg 构造函数。

如果需要为其他持久性技术利用这种机制,可以配置[`kotlin-noarg`](https://kotlinlang.org/docs/reference/compiler-plugins.html#how-to-use-no-arg-plugin)插件。

|   |在 Kay Release Train 中, Spring 数据支持 Kotlin 不可变类实例,并且如果模块使用 Spring 数据对象映射`kotlin-noarg`(例如 MongoDB、Redis、Cassandra 和其他),则`kotlin-noarg`不需要<gt r=“261”插件。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.3.注入依赖项

我们的建议是尝试使用`val`只读(并且在可能的情况下不可为空)[properties](https://kotlinlang.org/docs/reference/properties.html)的构造函数注入,如下例所示:

```
@Component
class YourBean(
    private val mongoTemplate: MongoTemplate,
    private val solrClient: SolrClient
)
```

|   |带有单个构造函数的类的参数自动自动连线。<br/>这就是为什么在上面的`@Autowired constructor`示例中不需要显式的`@Autowired constructor`的原因。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果确实需要使用字段注入,可以使用`lateinit var`构造,如下例所示:

```
@Component
class YourBean {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    @Autowired
    lateinit var solrClient: SolrClient
}
```

#### 1.9.4.注入配置属性

在 Java 中,你可以通过使用注释(例如`@Value("${property}")`)注入配置属性。然而,在 Kotlin 中,`# 语言支持

## 1. Kotlin

[Kotlin](https://kotlinlang.org)是一种以 JVM(和其他平台)为目标的静态类型语言,它允许编写简洁和优雅的代码,同时使用用 Java 编写的现有库提供非常好的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)。

Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序,就好像 Spring 框架是一个原生 Kotlin 框架一样。除了 Java 之外,参考文档的大多数代码示例都是在 Kotlin 中提供的。

用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring 引导和它的[dedicated Kotlin support](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-kotlin.html)。[这个全面的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)将教你如何使用[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)用 Kotlin 构建 Spring 引导应用程序。

如果你需要支持,可以随时加入[Kotlin Slack](https://slack.kotlinlang.org/)的 # Spring 通道,或者使用`spring`和`kotlin`作为标记在[Stackoverflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上提问。

### 1.1.所需经费

Spring 框架支持 Kotlin 1.3+,并且需要[`kotlin-stdlib`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib)(或其变体之一,例如[`kotlin-stdlib-jdk8`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8))和[`kotlin-reflect`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-reflect)才能在 Classpath 上存在。如果你在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上引导一个 Kotlin 项目,则默认情况下会提供它们。

|   |对于使用 Jackson 对 Kotlin 类的 JSON 数据进行序列化或反序列化,需要[Jackson Kotlin module](https://github.com/FasterXML/jackson-module-kotlin)<br/>,因此,如果你有此需要,请确保将 `com.fasterxml.Jackson.module:Jackson-module- Kotlin `dependency 添加到你的项目中。<br/>在 Classpath 中找到时,它会自动注册。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.2.扩展

Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html)提供了扩展具有附加功能的现有类的能力。 Spring 框架 Kotlin API 使用这些扩展来向现有 Spring API 添加新的 Kotlin 特定的便利。

[Spring Framework KDoc API](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/)列表和文档都是可用的 Kotlin 扩展和 DSL。

|   |请记住, Kotlin 扩展需要导入才能使用。这意味着,<br/>例如,`GenericApplicationContext.registerBean` Kotlin 扩展<br/>只有当`org.springframework.context.support.registerBean`被导入时才可用。<br/>也就是说,与静态导入类似,IDE 在大多数情况下应该自动建议导入。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

例如,[Kotlin reified type parameters](https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)为 JVM[泛型擦除](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)提供了一种变通方法,而 Spring 框架提供了一些扩展来利用这一特性。这允许更好的 Kotlin API`RestTemplate`、 Spring WebFlux 中的新`WebClient`以及其他各种 API。

|   |其他库,例如 Reactor 和 Spring Data,也为它们的 API 提供了 Kotlin 扩展,因此总体上提供了更好的 Kotlin 开发体验。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------|

要在 Java 中检索`User`对象的列表,通常需要编写以下内容:

```
Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
```

对于 Kotlin 和 Spring 框架扩展,你可以改为编写以下内容:

```
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
```

正如在 Java 中一样, Kotlin 中的`users`是强类型的,但是 Kotlin 聪明的类型推断允许更短的语法。

### 1.3.零安全

Kotlin 的关键特性之一是[null-safety](https://kotlinlang.org/docs/reference/null-safety.html),它在编译时干净地处理`null`值,而不是在运行时遇到著名的 `nullPointerexception’。这使得应用程序通过可否定性声明和表达“值或无值”语义而更安全,而不需要支付包装器的费用,例如`Optional`。( Kotlin 允许使用具有可空的值的函数结构。参见[comprehensive guide to Kotlin null-safety](https://www.baeldung.com/kotlin-null-safety)。)

虽然 Java 不允许在其类型系统中表示空安全,但 Spring 框架通过在`org.springframework.lang`包中声明的对工具友好的注释提供了[null-safety of the whole Spring Framework API](core.html#null-safety)。默认情况下,来自 Kotlin 中使用的 Java API 的类型被识别为[platform types](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types),对此可以放松空值检查。[Kotlin support for JSR-305 annotations](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)和 Spring 空值注释为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,并具有在编译时处理`null`相关问题的优点。

|   |诸如 Reactor 或 Spring Data 之类的库提供了空安全的 API 来利用此功能。|
|---|-----------------------------------------------------------------------------------------|

你可以通过添加`-Xjsr305`编译器标志和以下选项来配置 JSR-305 检查:`-Xjsr305={strict|warn|ignore}`

对于 Kotlin 版本 1.1+,默认行为与`-Xjsr305=warn`相同。在从 Spring API 推断出的 Kotlin 类型中,`strict`值需要将 Spring FrameworkAPI 的空安全性考虑在内,但在使用该值时,应该知道 Spring API 的零性声明即使在较小的版本之间也可以发展,并且将来可能会添加更多的检查。

|   |目前还不支持泛型类型参数、varargs 和数组元素的可空性,<br/>,但应该在即将发布的版本中支持。有关最新信息,请参见[this discussion](https://github.com/Kotlin/KEEP/issues/79)。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.4.类和接口

Spring 框架支持各种 Kotlin 构造,例如通过主构造函数实例化 Kotlin 类、不可变类数据绑定和具有默认值的函数可选参数。

Kotlin 通过专用的`KotlinReflectionParameterNameDiscoverer`来识别参数名称,该参数名称允许查找接口方法参数名称,而不需要在编译过程中启用 Java8`-parameters`编译器标志。

你可以将配置类声明为[顶层或嵌套的,但不是内部的](https://kotlinlang.org/docs/reference/nested-classes.html),因为后者需要对外部类的引用。

### 1.5.注解

Spring 框架还利用[Kotlin null-safety](https://kotlinlang.org/docs/reference/null-safety.html)来确定是否需要 HTTP 参数,而无需显式地定义`required`属性。这意味着`@RequestParam name: String?`被视为不需要,相反,`@RequestParam name: String`被视为需要。 Spring 消息传递`@Header`注释上也支持此功能。

以类似的方式, Spring  Bean 带有`@Autowired``@Bean``@Inject`的注入使用该信息来确定是否需要 Bean。

例如,`@Autowired lateinit var thing: Thing`意味着必须在应用程序上下文中注册类型`Thing`的 Bean,而`@Autowired lateinit var thing: Thing?`如果不存在这样的 Bean,则不会引发错误。

遵循相同的原则,`@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)`意味着类型`Toy`的 Bean 必须在应用程序上下文中注册,而类型`Car`的 Bean 可能存在,也可能不存在。同样的行为也适用于自动连线构造函数参数。

|   |如果在具有属性或主构造函数<br/>参数的类上使用 Bean 验证,则可能需要使用[注释使用-站点目标](https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets)<br/>,例如`@field:NotNull``@get:Size(min=5, max=15)`,如[这个堆栈溢出响应](https://stackoverflow.com/a/35853200/1092077)中所述。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.6. Bean 定义 DSL

Spring Framework 支持通过使用 lambdas 作为 XML 或 Java 配置的替代方案(`@configuration``@Bean`)以功能方式注册 bean。简而言之,它允许你用 lambda 注册 bean,lambda 充当`FactoryBean`。这种机制非常有效,因为它不需要任何反射或 CGlib 代理。

例如,在 Java 中,你可以编写以下内容:

```
class Foo {}

class Bar {
    private final Foo foo;
    public Bar(Foo foo) {
        this.foo = foo;
    }
}

GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Foo.class);
context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class)));
```

在 Kotlin 中,使用具体化的类型参数和`GenericApplicationContext` Kotlin 扩展,你可以改为编写以下内容:

```
class Foo

class Bar(private val foo: Foo)

val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean { Bar(it.getBean()) }
}
```

当类`Bar`只有一个构造函数时,你甚至可以只指定 Bean 类,构造函数参数将根据类型自动连线:

```
val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean<Bar>()
}
```

为了允许更多的声明性方法和更干净的语法, Spring Framework 提供了[Kotlin bean definition DSL](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/)它通过一个干净的声明性 API 声明`ApplicationContextInitializer`,它允许你处理配置文件和`Environment`,以自定义如何注册 bean。

在下面的示例中,请注意:

* 类型推理通常允许避免为 Bean 引用指定类型,如`ref("bazBean")`

* 在本例中,可以使用 Kotlin 顶级函数使用`bean(::myRouter)`之类的可调用引用来声明 bean。

* 当指定`bean<Bar>()``bean(::myRouter)`时,参数将按类型自动连线。

* 只有在`foobar`配置文件处于活动状态时,才会注册`FooBar` Bean

```
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)

val myBeans = beans {
    bean<Foo>()
    bean<Bar>()
    bean("bazBean") {
        Baz().apply {
            message = "Hello world"
        }
    }
    profile("foobar") {
        bean { FooBar(ref("bazBean")) }
    }
    bean(::myRouter)
}

fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router {
    // ...
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|

然后,你可以使用这个`beans()`函数在应用程序上下文中注册 bean,如下例所示:

```
val context = GenericApplicationContext().apply {
    myBeans.initialize(this)
    refresh()
}
```

|   |Spring boot 是基于 javaconfig 和[does not yet provide specific support for functional bean definition](https://github.com/spring-projects/spring-boot/issues/8115)<br/>,但可以通过 Spring boot 的`ApplicationContextInitializer`支持实验性地使用函数 Bean 定义。<br/>查看[这个堆栈溢出回答](https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685)以获得更多详细信息和最新信息。另见[Spring Fu incubator](https://github.com/spring-projects/spring-fu)中开发的实验 Kofu DSL。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.7.万维网

#### 1.7.1.路由器 DSL

Spring Framework 自带的路由器 DSL 有 3 种类型:

* WebMVC.FNDSL with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.servlet.function/router.html)

* webflux.FN[Reactive](web-reactive.html#webflux-fn)dsl with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/router.html)

* webflux.FN[Coroutines](#coroutines)dsl with[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)

这些 DSL 允许你编写干净且惯用的 Kotlin 代码来构建`RouterFunction`实例,如下例所示:

```
@Configuration
class RouterRouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = router {
        accept(TEXT_HTML).nest {
            GET("/") { ok().render("index") }
            GET("/sse") { ok().render("sse") }
            GET("/users", userHandler::findAllView)
        }
        "/api".nest {
            accept(APPLICATION_JSON).nest {
                GET("/users", userHandler::findAll)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::stream)
            }
        }
        resources("/**", ClassPathResource("static/"))
    }
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。当你需要根据动态数据(例如,来自数据库)注册路由时,这可能是有用的<br/>。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

具体例子见[MiXiT project](https://github.com/mixitconf/mixit/)

#### 1.7.2.MockMVC DSL

Kotlin DSL 通过 Kotlin 扩展提供,以便提供更惯用的 Kotlin API 并允许更好的可发现性(不使用静态方法)。

```
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
    secure = true
    accept = APPLICATION_JSON
    headers {
        contentLanguage = Locale.FRANCE
    }
    principal = Principal { "foo" }
}.andExpect {
    status { isOk }
    content { contentType(APPLICATION_JSON) }
    jsonPath("$.name") { value("Lee") }
    content { json("""{"someBoolean": false}""", false) }
}.andDo {
    print()
}
```

#### 1.7.3. Kotlin 脚本模板

Spring Framework 提供了一个[“ScriptemplateView”](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/script/ScriptTemplateView.html),它支持[JSR-223](https://www.jcp.org/en/jsr/detail?id=223)通过使用脚本引擎来呈现模板。

通过利用`scripting-jsr223`依赖关系,可以使用这样的特性来呈现带有[kotlinx.html](https://github.com/Kotlin/kotlinx.html)DSL 或 Kotlin 多行插值`String`的基于 Kotlin 的模板。

`build.gradle.kts`

```
dependencies {
        runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
```

配置通常使用`ScriptTemplateConfigurer``ScriptTemplateViewResolver`bean。

`KotlinScriptConfiguration.kt`

```
@Configuration
class KotlinScriptConfiguration {

    @Bean
    fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
        engineName = "kotlin"
        setScripts("scripts/render.kts")
        renderFunction = "render"
        isSharedEngine = false
    }

    @Bean
    fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
        setPrefix("templates/")
        setSuffix(".kts")
    }
}
```

有关更多详细信息,请参见[kotlin-script-templating](https://github.com/sdeleuze/kotlin-script-templating)示例项目。

#### 1.7.4. Kotlin 多平台序列化

在 Spring Framework5.3 中,[Kotlin multiplatform serialization](https://github.com/Kotlin/kotlinx.serialization)在 Spring MVC、 Spring WebFlux 和 Spring Messaging 中得到了支持。内置支持目前只针对 JSON 格式。

要启用它,请按照[那些指示](https://github.com/Kotlin/kotlinx.serialization#setup)添加相关的依赖项和插件。对于 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 Classpath 中,那么它们将默认地被配置,因为 Kotlin 序列化被设计为仅序列化 Kotlin 用`@Serializable`注释的类。使用 Spring 消息传递,如果你想要自动配置,则确保 Jackson、GSON 或 JSONB 都不在 Classpath 中,如果需要配置 Jackson,则手动配置`KotlinSerializationJsonMessageConverter`

### 1.8.协理

Kotlin [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)是 Kotlin 轻量级线程,允许以强制方式编写非阻塞代码。在语言端,挂起函数为异步操作提供了抽象,而在库端[Kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)提供了[`async { }`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html)之类的函数和[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)之类的类型。

Spring 框架在以下范围上为协程提供支持:

* [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)[Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)返回 Spring MVC 和 WebFlux 中支持的值,注释`@Controller`

* Spring MVC 和 WebFlux 注释`@Controller`中的挂起功能支持

* WebFlux[client](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.client/index.html)[server](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/index.html)函数 API 的扩展。

* WebFlux.FN[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL

* 挂起函数和`Flow`在 RSocket 中支持`@MessageMapping`注释方法

* [rsocketrequester’](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.messaging.rsocket/index.html)的扩展

#### 1.8.1.依赖关系

`kotlinx-coroutines-core``kotlinx-coroutines-reactor`依赖项位于 Classpath 中时,将启用协程支持:

`build.gradle.kts`

```
dependencies {

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}")
}
```

支持`1.4.0`及以上版本。

#### 1.8.2.反应性如何转化为协程?

对于返回值,从 Active 到 CoroutineAPI 的转换如下:

* `fun handler(): Mono<Void>`变为`suspend fun handler()`

* `fun handler(): Mono<T>`变为`suspend fun handler(): T``suspend fun handler(): T?`取决于`Mono`是否为空(具有更静态类型的优点)

* `fun handler(): Flux<T>`变为`fun handler(): Flow<T>`

输入参数:

* 如果不需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(value: T)`,因为可以调用挂起的函数来获得值参数。

* 如果需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(supplier: suspend () → T)``fun handler(supplier: suspend () → T?)`

[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在协程世界中是`Flux`等价的,适用于冷热气流、有限气流或无限气流,有以下主要区别:

* `Flow`是推拉式的,而`Flux`是推拉式的混合动力

* 背压是通过悬挂功能实现的。

* `Flow`只有一个[single suspending `collect` method](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html),运算符实现为[extensions](https://kotlinlang.org/docs/reference/extensions.html)

* [运营商很容易实现。](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common/src/flow/operators)感谢协程

* 扩展允许将自定义运算符添加到`Flow`

* 收集操作是挂起的功能

* [`map` operator](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html)支持异步操作(不需要`flatMap`),因为它需要一个挂起的函数参数

阅读这篇关于[Going Reactive with Spring, Coroutines and Kotlin Flow](https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow)的博客文章,了解更多详细信息,包括如何与协程同时运行代码。

#### 1.8.3.控制器

下面是一个协程`@RestController`的例子。

```
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {

    @GetMapping("/suspend")
    suspend fun suspendingEndpoint(): Banner {
        delay(10)
        return banner
    }

    @GetMapping("/flow")
    fun flowEndpoint() = flow {
        delay(10)
        emit(banner)
        delay(10)
        emit(banner)
    }

    @GetMapping("/deferred")
    fun deferredEndpoint() = GlobalScope.async {
        delay(10)
        banner
    }

    @GetMapping("/sequential")
    suspend fun sequential(): List<Banner> {
        val banner1 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        val banner2 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        return listOf(banner1, banner2)
    }

    @GetMapping("/parallel")
    suspend fun parallel(): List<Banner> = coroutineScope {
        val deferredBanner1: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        val deferredBanner2: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        listOf(deferredBanner1.await(), deferredBanner2.await())
    }

    @GetMapping("/error")
    suspend fun error() {
        throw IllegalStateException()
    }

    @GetMapping("/cancel")
    suspend fun cancel() {
        throw CancellationException()
    }

}
```

还支持`@Controller`的视图呈现。

```
@Controller
class CoroutinesViewController(banner: Banner) {

    @GetMapping("/")
    suspend fun render(model: Model): String {
        delay(10)
        model["banner"] = banner
        return "index"
    }
}
```

#### 1.8.4.WebFlux.FN

下面是通过[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL 和相关处理程序定义的协程路由器的示例。

```
@Configuration
class RouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = coRouter {
        GET("/", userHandler::listView)
        GET("/api/user", userHandler::listApi)
    }
}
```

```
class UserHandler(builder: WebClient.Builder) {

    private val client = builder.baseUrl("...").build()

    suspend fun listView(request: ServerRequest): ServerResponse =
            ServerResponse.ok().renderAndAwait("users", mapOf("users" to
            client.get().uri("...").awaitExchange().awaitBody<User>()))

    suspend fun listApi(request: ServerRequest): ServerResponse =
                ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
                client.get().uri("...").awaitExchange().awaitBody<User>())
}
```

#### 1.8.5.交易

通过 Spring 框架 5.2 提供的反应式事务管理的编程变体,支持协程上的事务。

对于挂起的函数,提供了`TransactionalOperator.executeAndAwait`扩展。

```
import org.springframework.transaction.reactive.executeAndAwait

class PersonRepository(private val operator: TransactionalOperator) {

    suspend fun initDatabase() = operator.executeAndAwait {
        insertPerson1()
        insertPerson2()
    }

    private suspend fun insertPerson1() {
        // INSERT SQL statement
    }

    private suspend fun insertPerson2() {
        // INSERT SQL statement
    }
}
```

对于 Kotlin `Flow`,提供了一个`Flow<T>.transactional`扩展。

```
import org.springframework.transaction.reactive.transactional

class PersonRepository(private val operator: TransactionalOperator) {

    fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)

    private fun findPeople(): Flow<Person> {
        // SELECT SQL statement
    }

    private suspend fun updatePerson(person: Person): Person {
        // UPDATE SQL statement
    }
}
```

### 1.9. Spring  Kotlin 中的项目

本节提供了一些值得在 Kotlin 中开发 Spring 项目的具体提示和建议。

#### 1.9.1.默认情况下为 final

默认情况下,[all classes in Kotlin are `final`](https://discuss.kotlinlang.org/t/classes-final-by-default/166)。类上的`open`修饰符与 Java 的`final`相反:它允许其他人继承这个类。这也适用于成员函数,因为它们需要标记为`open`才能被重写。

虽然 Kotlin 的 JVM 友好设计通常与 Spring 无摩擦,但如果不考虑这一事实,则此特定的 Kotlin 特性可以阻止应用程序启动。这是因为 Spring bean(例如`@Configuration`注释类,由于技术原因,默认情况下需要在运行时进行扩展)通常是由 CGLIB 代理的。解决方法是在 Spring bean 的每个类和成员函数上添加一个`open`关键字,这些类和成员函数是由 CGlib 代理的,这可能很快会变得很痛苦,并且违反 Kotlin 保持代码简洁和可预测的原则。

|   |也可以通过使用`@Configuration(proxyBeanMethods = false)`来避免配置类的 CGLIB 代理。<br/>查看[“ProxyBeanMethods”Javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html#proxyBeanMethods--)以获得更多详细信息。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

幸运的是, Kotlin 提供了一个[`kotlin-spring`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin)插件(`kotlin-allopen`插件的预先配置版本),该插件自动为使用以下注释之一进行注释或元注释的类型打开类及其成员函数:

* `@Component`

* `@Async`

* `@Transactional`

* `@Cacheable`

元注释支持意味着使用`@Configuration``@Controller`、<restcontroller`、或`@Repository`进行注释的类型将自动打开,因为这些注释是用`@Component`进行元注释的。

[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)默认情况下启用`kotlin-spring`插件。因此,在实践中,你可以在不添加任何`open`关键字的情况下编写 Kotlin bean,就像在 Java 中一样。

|   |Spring 框架文档中的 Kotlin 代码示例并未在类及其成员函数上明确指定“open”。示例是使用`kotlin-allopen`插件为<br/>项目编写的,因为这是最常用的设置。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.2.使用不可变类实例实现持久性

在 Kotlin 中,在主构造函数中声明只读属性是很方便的,并且被认为是一种最佳实践,如下例所示:

```
class Person(val name: String, val age: Int)
```

你可以选择添加[the `data` keyword](https://kotlinlang.org/docs/reference/data-classes.html),以使编译器自动从主构造函数中声明的所有属性派生出以下成员:

* `equals()`和`hashCode()`

* `toString()`的形式`"User(name=John, age=42)"`

* `componentN()`与其声明顺序中的属性对应的函数

* `copy()`函数

正如下面的示例所示,这允许对单个属性进行简单的更改,即使`Person`属性是只读的:

```
data class Person(val name: String, val age: Int)

val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
```

常见的持久性技术(例如 JPA)需要一个默认的构造函数,从而阻止了这种设计。幸运的是,对于这个[“默认构造函数地狱”](https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell)有一种解决方法,因为 Kotlin 提供了一个[`kotlin-jpa`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-jpa-compiler-plugin)插件,该插件为带有 JPA 注释的类生成合成的无 arg 构造函数。

如果需要为其他持久性技术利用这种机制,可以配置[`kotlin-noarg`](https://kotlinlang.org/docs/reference/compiler-plugins.html#how-to-use-no-arg-plugin)插件。

|   |在 Kay Release Train 中, Spring 数据支持 Kotlin 不可变类实例,并且如果模块使用 Spring 数据对象映射`kotlin-noarg`(例如 MongoDB、Redis、Cassandra 和其他),则`kotlin-noarg`不需要<gt r=“261”插件。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.3.注入依赖项

我们的建议是尝试使用`val`只读(并且在可能的情况下不可为空)[properties](https://kotlinlang.org/docs/reference/properties.html)的构造函数注入,如下例所示:

```
@Component
class YourBean(
    private val mongoTemplate: MongoTemplate,
    private val solrClient: SolrClient
)
```

|   |带有单个构造函数的类的参数自动自动连线。<br/>这就是为什么在上面的`@Autowired constructor`示例中不需要显式的`@Autowired constructor`的原因。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果确实需要使用字段注入,可以使用`lateinit var`构造,如下例所示:

```
@Component
class YourBean {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    @Autowired
    lateinit var solrClient: SolrClient
}
```

#### 1.9.4.注入配置属性

是用于[字符串插值](https://kotlinlang.org/docs/reference/idioms.html#string-interpolation)的保留字符。

因此,如果希望在 Kotlin 中使用`@Value`注释,则需要通过写`@Value("\${property}")`来转义`# 语言支持

## 1. Kotlin

[Kotlin](https://kotlinlang.org)是一种以 JVM(和其他平台)为目标的静态类型语言,它允许编写简洁和优雅的代码,同时使用用 Java 编写的现有库提供非常好的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)

Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序,就好像 Spring 框架是一个原生 Kotlin 框架一样。除了 Java 之外,参考文档的大多数代码示例都是在 Kotlin 中提供的。

用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring 引导和它的[dedicated Kotlin support](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-kotlin.html)[这个全面的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)将教你如何使用[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)用 Kotlin 构建 Spring 引导应用程序。

如果你需要支持,可以随时加入[Kotlin Slack](https://slack.kotlinlang.org/)的 # Spring 通道,或者使用`spring``kotlin`作为标记在[Stackoverflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上提问。

### 1.1.所需经费

Spring 框架支持 Kotlin 1.3+,并且需要[`kotlin-stdlib`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib)(或其变体之一,例如[`kotlin-stdlib-jdk8`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8))和[`kotlin-reflect`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-reflect)才能在 Classpath 上存在。如果你在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上引导一个 Kotlin 项目,则默认情况下会提供它们。

|   |对于使用 Jackson 对 Kotlin 类的 JSON 数据进行序列化或反序列化,需要[Jackson Kotlin module](https://github.com/FasterXML/jackson-module-kotlin)<br/>,因此,如果你有此需要,请确保将 `com.fasterxml.Jackson.module:Jackson-module- Kotlin `dependency 添加到你的项目中。<br/>在 Classpath 中找到时,它会自动注册。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.2.扩展

Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html)提供了扩展具有附加功能的现有类的能力。 Spring 框架 Kotlin API 使用这些扩展来向现有 Spring API 添加新的 Kotlin 特定的便利。

[Spring Framework KDoc API](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/)列表和文档都是可用的 Kotlin 扩展和 DSL。

|   |请记住, Kotlin 扩展需要导入才能使用。这意味着,<br/>例如,`GenericApplicationContext.registerBean` Kotlin 扩展<br/>只有当`org.springframework.context.support.registerBean`被导入时才可用。<br/>也就是说,与静态导入类似,IDE 在大多数情况下应该自动建议导入。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

例如,[Kotlin reified type parameters](https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)为 JVM[泛型擦除](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)提供了一种变通方法,而 Spring 框架提供了一些扩展来利用这一特性。这允许更好的 Kotlin API`RestTemplate`、 Spring WebFlux 中的新`WebClient`以及其他各种 API。

|   |其他库,例如 Reactor 和 Spring Data,也为它们的 API 提供了 Kotlin 扩展,因此总体上提供了更好的 Kotlin 开发体验。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------|

要在 Java 中检索`User`对象的列表,通常需要编写以下内容:

```
Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
```

对于 Kotlin 和 Spring 框架扩展,你可以改为编写以下内容:

```
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
```

正如在 Java 中一样, Kotlin 中的`users`是强类型的,但是 Kotlin 聪明的类型推断允许更短的语法。

### 1.3.零安全

Kotlin 的关键特性之一是[null-safety](https://kotlinlang.org/docs/reference/null-safety.html),它在编译时干净地处理`null`值,而不是在运行时遇到著名的 `nullPointerexception’。这使得应用程序通过可否定性声明和表达“值或无值”语义而更安全,而不需要支付包装器的费用,例如`Optional`。( Kotlin 允许使用具有可空的值的函数结构。参见[comprehensive guide to Kotlin null-safety](https://www.baeldung.com/kotlin-null-safety)。)

虽然 Java 不允许在其类型系统中表示空安全,但 Spring 框架通过在`org.springframework.lang`包中声明的对工具友好的注释提供了[null-safety of the whole Spring Framework API](core.html#null-safety)。默认情况下,来自 Kotlin 中使用的 Java API 的类型被识别为[platform types](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types),对此可以放松空值检查。[Kotlin support for JSR-305 annotations](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)和 Spring 空值注释为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,并具有在编译时处理`null`相关问题的优点。

|   |诸如 Reactor 或 Spring Data 之类的库提供了空安全的 API 来利用此功能。|
|---|-----------------------------------------------------------------------------------------|

你可以通过添加`-Xjsr305`编译器标志和以下选项来配置 JSR-305 检查:`-Xjsr305={strict|warn|ignore}`。

对于 Kotlin 版本 1.1+,默认行为与`-Xjsr305=warn`相同。在从 Spring API 推断出的 Kotlin 类型中,`strict`值需要将 Spring FrameworkAPI 的空安全性考虑在内,但在使用该值时,应该知道 Spring API 的零性声明即使在较小的版本之间也可以发展,并且将来可能会添加更多的检查。

|   |目前还不支持泛型类型参数、varargs 和数组元素的可空性,<br/>,但应该在即将发布的版本中支持。有关最新信息,请参见[this discussion](https://github.com/Kotlin/KEEP/issues/79)。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.4.类和接口

Spring 框架支持各种 Kotlin 构造,例如通过主构造函数实例化 Kotlin 类、不可变类数据绑定和具有默认值的函数可选参数。

Kotlin 通过专用的`KotlinReflectionParameterNameDiscoverer`来识别参数名称,该参数名称允许查找接口方法参数名称,而不需要在编译过程中启用 Java8`-parameters`编译器标志。

你可以将配置类声明为[顶层或嵌套的,但不是内部的](https://kotlinlang.org/docs/reference/nested-classes.html),因为后者需要对外部类的引用。

### 1.5.注解

Spring 框架还利用[Kotlin null-safety](https://kotlinlang.org/docs/reference/null-safety.html)来确定是否需要 HTTP 参数,而无需显式地定义`required`属性。这意味着`@RequestParam name: String?`被视为不需要,相反,`@RequestParam name: String`被视为需要。 Spring 消息传递`@Header`注释上也支持此功能。

以类似的方式, Spring  Bean 带有`@Autowired`、`@Bean`或`@Inject`的注入使用该信息来确定是否需要 Bean。

例如,`@Autowired lateinit var thing: Thing`意味着必须在应用程序上下文中注册类型`Thing`的 Bean,而`@Autowired lateinit var thing: Thing?`如果不存在这样的 Bean,则不会引发错误。

遵循相同的原则,`@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)`意味着类型`Toy`的 Bean 必须在应用程序上下文中注册,而类型`Car`的 Bean 可能存在,也可能不存在。同样的行为也适用于自动连线构造函数参数。

|   |如果在具有属性或主构造函数<br/>参数的类上使用 Bean 验证,则可能需要使用[注释使用-站点目标](https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets),<br/>,例如`@field:NotNull`或`@get:Size(min=5, max=15)`,如[这个堆栈溢出响应](https://stackoverflow.com/a/35853200/1092077)中所述。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.6. Bean 定义 DSL

Spring Framework 支持通过使用 lambdas 作为 XML 或 Java 配置的替代方案(`@configuration` 和`@Bean`)以功能方式注册 bean。简而言之,它允许你用 lambda 注册 bean,lambda 充当`FactoryBean`。这种机制非常有效,因为它不需要任何反射或 CGlib 代理。

例如,在 Java 中,你可以编写以下内容:

```
class Foo {}

class Bar {
    private final Foo foo;
    public Bar(Foo foo) {
        this.foo = foo;
    }
}

GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Foo.class);
context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class)));
```

在 Kotlin 中,使用具体化的类型参数和`GenericApplicationContext` Kotlin 扩展,你可以改为编写以下内容:

```
class Foo

class Bar(private val foo: Foo)

val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean { Bar(it.getBean()) }
}
```

当类`Bar`只有一个构造函数时,你甚至可以只指定 Bean 类,构造函数参数将根据类型自动连线:

```
val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean<Bar>()
}
```

为了允许更多的声明性方法和更干净的语法, Spring Framework 提供了[Kotlin bean definition DSL](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/)它通过一个干净的声明性 API 声明`ApplicationContextInitializer`,它允许你处理配置文件和`Environment`,以自定义如何注册 bean。

在下面的示例中,请注意:

* 类型推理通常允许避免为 Bean 引用指定类型,如`ref("bazBean")`

* 在本例中,可以使用 Kotlin 顶级函数使用`bean(::myRouter)`之类的可调用引用来声明 bean。

* 当指定`bean<Bar>()`或`bean(::myRouter)`时,参数将按类型自动连线。

* 只有在`foobar`配置文件处于活动状态时,才会注册`FooBar` Bean

```
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)

val myBeans = beans {
    bean<Foo>()
    bean<Bar>()
    bean("bazBean") {
        Baz().apply {
            message = "Hello world"
        }
    }
    profile("foobar") {
        bean { FooBar(ref("bazBean")) }
    }
    bean(::myRouter)
}

fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router {
    // ...
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|

然后,你可以使用这个`beans()`函数在应用程序上下文中注册 bean,如下例所示:

```
val context = GenericApplicationContext().apply {
    myBeans.initialize(this)
    refresh()
}
```

|   |Spring boot 是基于 javaconfig 和[does not yet provide specific support for functional bean definition](https://github.com/spring-projects/spring-boot/issues/8115),<br/>,但可以通过 Spring boot 的`ApplicationContextInitializer`支持实验性地使用函数 Bean 定义。<br/>查看[这个堆栈溢出回答](https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685)以获得更多详细信息和最新信息。另见[Spring Fu incubator](https://github.com/spring-projects/spring-fu)中开发的实验 Kofu DSL。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.7.万维网

#### 1.7.1.路由器 DSL

Spring Framework 自带的路由器 DSL 有 3 种类型:

* WebMVC.FNDSL with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.servlet.function/router.html)

* webflux.FN[Reactive](web-reactive.html#webflux-fn)dsl with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/router.html)

* webflux.FN[Coroutines](#coroutines)dsl with[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)

这些 DSL 允许你编写干净且惯用的 Kotlin 代码来构建`RouterFunction`实例,如下例所示:

```
@Configuration
class RouterRouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = router {
        accept(TEXT_HTML).nest {
            GET("/") { ok().render("index") }
            GET("/sse") { ok().render("sse") }
            GET("/users", userHandler::findAllView)
        }
        "/api".nest {
            accept(APPLICATION_JSON).nest {
                GET("/users", userHandler::findAll)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::stream)
            }
        }
        resources("/**", ClassPathResource("static/"))
    }
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。当你需要根据动态数据(例如,来自数据库)注册路由时,这可能是有用的<br/>。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

具体例子见[MiXiT project](https://github.com/mixitconf/mixit/)。

#### 1.7.2.MockMVC DSL

Kotlin DSL 通过 Kotlin 扩展提供,以便提供更惯用的 Kotlin API 并允许更好的可发现性(不使用静态方法)。

```
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
    secure = true
    accept = APPLICATION_JSON
    headers {
        contentLanguage = Locale.FRANCE
    }
    principal = Principal { "foo" }
}.andExpect {
    status { isOk }
    content { contentType(APPLICATION_JSON) }
    jsonPath("$.name") { value("Lee") }
    content { json("""{"someBoolean": false}""", false) }
}.andDo {
    print()
}
```

#### 1.7.3. Kotlin 脚本模板

Spring Framework 提供了一个[“ScriptemplateView”](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/script/ScriptTemplateView.html),它支持[JSR-223](https://www.jcp.org/en/jsr/detail?id=223)通过使用脚本引擎来呈现模板。

通过利用`scripting-jsr223`依赖关系,可以使用这样的特性来呈现带有[kotlinx.html](https://github.com/Kotlin/kotlinx.html)DSL 或 Kotlin 多行插值`String`的基于 Kotlin 的模板。

`build.gradle.kts`

```
dependencies {
        runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
```

配置通常使用`ScriptTemplateConfigurer`和`ScriptTemplateViewResolver`bean。

`KotlinScriptConfiguration.kt`

```
@Configuration
class KotlinScriptConfiguration {

    @Bean
    fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
        engineName = "kotlin"
        setScripts("scripts/render.kts")
        renderFunction = "render"
        isSharedEngine = false
    }

    @Bean
    fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
        setPrefix("templates/")
        setSuffix(".kts")
    }
}
```

有关更多详细信息,请参见[kotlin-script-templating](https://github.com/sdeleuze/kotlin-script-templating)示例项目。

#### 1.7.4. Kotlin 多平台序列化

在 Spring Framework5.3 中,[Kotlin multiplatform serialization](https://github.com/Kotlin/kotlinx.serialization)在 Spring MVC、 Spring WebFlux 和 Spring Messaging 中得到了支持。内置支持目前只针对 JSON 格式。

要启用它,请按照[那些指示](https://github.com/Kotlin/kotlinx.serialization#setup)添加相关的依赖项和插件。对于 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 Classpath 中,那么它们将默认地被配置,因为 Kotlin 序列化被设计为仅序列化 Kotlin 用`@Serializable`注释的类。使用 Spring 消息传递,如果你想要自动配置,则确保 Jackson、GSON 或 JSONB 都不在 Classpath 中,如果需要配置 Jackson,则手动配置`KotlinSerializationJsonMessageConverter`。

### 1.8.协理

Kotlin [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)是 Kotlin 轻量级线程,允许以强制方式编写非阻塞代码。在语言端,挂起函数为异步操作提供了抽象,而在库端[Kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)提供了[`async { }`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html)之类的函数和[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)之类的类型。

Spring 框架在以下范围上为协程提供支持:

* [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)和[Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)返回 Spring MVC 和 WebFlux 中支持的值,注释`@Controller`

* Spring MVC 和 WebFlux 注释`@Controller`中的挂起功能支持

* WebFlux[client](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.client/index.html)和[server](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/index.html)函数 API 的扩展。

* WebFlux.FN[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL

* 挂起函数和`Flow`在 RSocket 中支持`@MessageMapping`注释方法

* [rsocketrequester’](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.messaging.rsocket/index.html)的扩展

#### 1.8.1.依赖关系

当`kotlinx-coroutines-core`和`kotlinx-coroutines-reactor`依赖项位于 Classpath 中时,将启用协程支持:

`build.gradle.kts`

```
dependencies {

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}")
}
```

支持`1.4.0`及以上版本。

#### 1.8.2.反应性如何转化为协程?

对于返回值,从 Active 到 CoroutineAPI 的转换如下:

* `fun handler(): Mono<Void>`变为`suspend fun handler()`

* `fun handler(): Mono<T>`变为`suspend fun handler(): T`或`suspend fun handler(): T?`取决于`Mono`是否为空(具有更静态类型的优点)

* `fun handler(): Flux<T>`变为`fun handler(): Flow<T>`

输入参数:

* 如果不需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(value: T)`,因为可以调用挂起的函数来获得值参数。

* 如果需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(supplier: suspend () → T)`或`fun handler(supplier: suspend () → T?)`

[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在协程世界中是`Flux`等价的,适用于冷热气流、有限气流或无限气流,有以下主要区别:

* `Flow`是推拉式的,而`Flux`是推拉式的混合动力

* 背压是通过悬挂功能实现的。

* `Flow`只有一个[single suspending `collect` method](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html),运算符实现为[extensions](https://kotlinlang.org/docs/reference/extensions.html)

* [运营商很容易实现。](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common/src/flow/operators)感谢协程

* 扩展允许将自定义运算符添加到`Flow`

* 收集操作是挂起的功能

* [`map` operator](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html)支持异步操作(不需要`flatMap`),因为它需要一个挂起的函数参数

阅读这篇关于[Going Reactive with Spring, Coroutines and Kotlin Flow](https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow)的博客文章,了解更多详细信息,包括如何与协程同时运行代码。

#### 1.8.3.控制器

下面是一个协程`@RestController`的例子。

```
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {

    @GetMapping("/suspend")
    suspend fun suspendingEndpoint(): Banner {
        delay(10)
        return banner
    }

    @GetMapping("/flow")
    fun flowEndpoint() = flow {
        delay(10)
        emit(banner)
        delay(10)
        emit(banner)
    }

    @GetMapping("/deferred")
    fun deferredEndpoint() = GlobalScope.async {
        delay(10)
        banner
    }

    @GetMapping("/sequential")
    suspend fun sequential(): List<Banner> {
        val banner1 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        val banner2 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        return listOf(banner1, banner2)
    }

    @GetMapping("/parallel")
    suspend fun parallel(): List<Banner> = coroutineScope {
        val deferredBanner1: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        val deferredBanner2: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        listOf(deferredBanner1.await(), deferredBanner2.await())
    }

    @GetMapping("/error")
    suspend fun error() {
        throw IllegalStateException()
    }

    @GetMapping("/cancel")
    suspend fun cancel() {
        throw CancellationException()
    }

}
```

还支持`@Controller`的视图呈现。

```
@Controller
class CoroutinesViewController(banner: Banner) {

    @GetMapping("/")
    suspend fun render(model: Model): String {
        delay(10)
        model["banner"] = banner
        return "index"
    }
}
```

#### 1.8.4.WebFlux.FN

下面是通过[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL 和相关处理程序定义的协程路由器的示例。

```
@Configuration
class RouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = coRouter {
        GET("/", userHandler::listView)
        GET("/api/user", userHandler::listApi)
    }
}
```

```
class UserHandler(builder: WebClient.Builder) {

    private val client = builder.baseUrl("...").build()

    suspend fun listView(request: ServerRequest): ServerResponse =
            ServerResponse.ok().renderAndAwait("users", mapOf("users" to
            client.get().uri("...").awaitExchange().awaitBody<User>()))

    suspend fun listApi(request: ServerRequest): ServerResponse =
                ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
                client.get().uri("...").awaitExchange().awaitBody<User>())
}
```

#### 1.8.5.交易

通过 Spring 框架 5.2 提供的反应式事务管理的编程变体,支持协程上的事务。

对于挂起的函数,提供了`TransactionalOperator.executeAndAwait`扩展。

```
import org.springframework.transaction.reactive.executeAndAwait

class PersonRepository(private val operator: TransactionalOperator) {

    suspend fun initDatabase() = operator.executeAndAwait {
        insertPerson1()
        insertPerson2()
    }

    private suspend fun insertPerson1() {
        // INSERT SQL statement
    }

    private suspend fun insertPerson2() {
        // INSERT SQL statement
    }
}
```

对于 Kotlin `Flow`,提供了一个`Flow<T>.transactional`扩展。

```
import org.springframework.transaction.reactive.transactional

class PersonRepository(private val operator: TransactionalOperator) {

    fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)

    private fun findPeople(): Flow<Person> {
        // SELECT SQL statement
    }

    private suspend fun updatePerson(person: Person): Person {
        // UPDATE SQL statement
    }
}
```

### 1.9. Spring  Kotlin 中的项目

本节提供了一些值得在 Kotlin 中开发 Spring 项目的具体提示和建议。

#### 1.9.1.默认情况下为 final

默认情况下,[all classes in Kotlin are `final`](https://discuss.kotlinlang.org/t/classes-final-by-default/166)。类上的`open`修饰符与 Java 的`final`相反:它允许其他人继承这个类。这也适用于成员函数,因为它们需要标记为`open`才能被重写。

虽然 Kotlin 的 JVM 友好设计通常与 Spring 无摩擦,但如果不考虑这一事实,则此特定的 Kotlin 特性可以阻止应用程序启动。这是因为 Spring bean(例如`@Configuration`注释类,由于技术原因,默认情况下需要在运行时进行扩展)通常是由 CGLIB 代理的。解决方法是在 Spring bean 的每个类和成员函数上添加一个`open`关键字,这些类和成员函数是由 CGlib 代理的,这可能很快会变得很痛苦,并且违反 Kotlin 保持代码简洁和可预测的原则。

|   |也可以通过使用`@Configuration(proxyBeanMethods = false)`来避免配置类的 CGLIB 代理。<br/>查看[“ProxyBeanMethods”Javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html#proxyBeanMethods--)以获得更多详细信息。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

幸运的是, Kotlin 提供了一个[`kotlin-spring`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin)插件(`kotlin-allopen`插件的预先配置版本),该插件自动为使用以下注释之一进行注释或元注释的类型打开类及其成员函数:

* `@Component`

* `@Async`

* `@Transactional`

* `@Cacheable`

元注释支持意味着使用`@Configuration`、`@Controller`、<restcontroller`、或`@Repository`进行注释的类型将自动打开,因为这些注释是用`@Component`进行元注释的。

[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)默认情况下启用`kotlin-spring`插件。因此,在实践中,你可以在不添加任何`open`关键字的情况下编写 Kotlin bean,就像在 Java 中一样。

|   |Spring 框架文档中的 Kotlin 代码示例并未在类及其成员函数上明确指定“open”。示例是使用`kotlin-allopen`插件为<br/>项目编写的,因为这是最常用的设置。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.2.使用不可变类实例实现持久性

在 Kotlin 中,在主构造函数中声明只读属性是很方便的,并且被认为是一种最佳实践,如下例所示:

```
class Person(val name: String, val age: Int)
```

你可以选择添加[the `data` keyword](https://kotlinlang.org/docs/reference/data-classes.html),以使编译器自动从主构造函数中声明的所有属性派生出以下成员:

* `equals()``hashCode()`

* `toString()`的形式`"User(name=John, age=42)"`

* `componentN()`与其声明顺序中的属性对应的函数

* `copy()`函数

正如下面的示例所示,这允许对单个属性进行简单的更改,即使`Person`属性是只读的:

```
data class Person(val name: String, val age: Int)

val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
```

常见的持久性技术(例如 JPA)需要一个默认的构造函数,从而阻止了这种设计。幸运的是,对于这个[“默认构造函数地狱”](https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell)有一种解决方法,因为 Kotlin 提供了一个[`kotlin-jpa`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-jpa-compiler-plugin)插件,该插件为带有 JPA 注释的类生成合成的无 arg 构造函数。

如果需要为其他持久性技术利用这种机制,可以配置[`kotlin-noarg`](https://kotlinlang.org/docs/reference/compiler-plugins.html#how-to-use-no-arg-plugin)插件。

|   |在 Kay Release Train 中, Spring 数据支持 Kotlin 不可变类实例,并且如果模块使用 Spring 数据对象映射`kotlin-noarg`(例如 MongoDB、Redis、Cassandra 和其他),则`kotlin-noarg`不需要<gt r=“261”插件。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.3.注入依赖项

我们的建议是尝试使用`val`只读(并且在可能的情况下不可为空)[properties](https://kotlinlang.org/docs/reference/properties.html)的构造函数注入,如下例所示:

```
@Component
class YourBean(
    private val mongoTemplate: MongoTemplate,
    private val solrClient: SolrClient
)
```

|   |带有单个构造函数的类的参数自动自动连线。<br/>这就是为什么在上面的`@Autowired constructor`示例中不需要显式的`@Autowired constructor`的原因。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果确实需要使用字段注入,可以使用`lateinit var`构造,如下例所示:

```
@Component
class YourBean {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    @Autowired
    lateinit var solrClient: SolrClient
}
```

#### 1.9.4.注入配置属性

在 Java 中,你可以通过使用注释(例如`@Value("${property}")`)注入配置属性。然而,在 Kotlin 中,`# 语言支持

## 1. Kotlin

[Kotlin](https://kotlinlang.org)是一种以 JVM(和其他平台)为目标的静态类型语言,它允许编写简洁和优雅的代码,同时使用用 Java 编写的现有库提供非常好的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)。

Spring 框架为 Kotlin 提供了一流的支持,并允许开发人员编写 Kotlin 应用程序,就好像 Spring 框架是一个原生 Kotlin 框架一样。除了 Java 之外,参考文档的大多数代码示例都是在 Kotlin 中提供的。

用 Kotlin 构建 Spring 应用程序的最简单方法是利用 Spring 引导和它的[dedicated Kotlin support](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-kotlin.html)。[这个全面的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)将教你如何使用[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)用 Kotlin 构建 Spring 引导应用程序。

如果你需要支持,可以随时加入[Kotlin Slack](https://slack.kotlinlang.org/)的 # Spring 通道,或者使用`spring`和`kotlin`作为标记在[Stackoverflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上提问。

### 1.1.所需经费

Spring 框架支持 Kotlin 1.3+,并且需要[`kotlin-stdlib`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib)(或其变体之一,例如[`kotlin-stdlib-jdk8`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8))和[`kotlin-reflect`](https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-reflect)才能在 Classpath 上存在。如果你在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上引导一个 Kotlin 项目,则默认情况下会提供它们。

|   |对于使用 Jackson 对 Kotlin 类的 JSON 数据进行序列化或反序列化,需要[Jackson Kotlin module](https://github.com/FasterXML/jackson-module-kotlin)<br/>,因此,如果你有此需要,请确保将 `com.fasterxml.Jackson.module:Jackson-module- Kotlin `dependency 添加到你的项目中。<br/>在 Classpath 中找到时,它会自动注册。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.2.扩展

Kotlin [extensions](https://kotlinlang.org/docs/reference/extensions.html)提供了扩展具有附加功能的现有类的能力。 Spring 框架 Kotlin API 使用这些扩展来向现有 Spring API 添加新的 Kotlin 特定的便利。

[Spring Framework KDoc API](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/)列表和文档都是可用的 Kotlin 扩展和 DSL。

|   |请记住, Kotlin 扩展需要导入才能使用。这意味着,<br/>例如,`GenericApplicationContext.registerBean` Kotlin 扩展<br/>只有当`org.springframework.context.support.registerBean`被导入时才可用。<br/>也就是说,与静态导入类似,IDE 在大多数情况下应该自动建议导入。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

例如,[Kotlin reified type parameters](https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)为 JVM[泛型擦除](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)提供了一种变通方法,而 Spring 框架提供了一些扩展来利用这一特性。这允许更好的 Kotlin API`RestTemplate`、 Spring WebFlux 中的新`WebClient`以及其他各种 API。

|   |其他库,例如 Reactor 和 Spring Data,也为它们的 API 提供了 Kotlin 扩展,因此总体上提供了更好的 Kotlin 开发体验。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------|

要在 Java 中检索`User`对象的列表,通常需要编写以下内容:

```
Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
```

对于 Kotlin 和 Spring 框架扩展,你可以改为编写以下内容:

```
val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()
```

正如在 Java 中一样, Kotlin 中的`users`是强类型的,但是 Kotlin 聪明的类型推断允许更短的语法。

### 1.3.零安全

Kotlin 的关键特性之一是[null-safety](https://kotlinlang.org/docs/reference/null-safety.html),它在编译时干净地处理`null`值,而不是在运行时遇到著名的 `nullPointerexception’。这使得应用程序通过可否定性声明和表达“值或无值”语义而更安全,而不需要支付包装器的费用,例如`Optional`。( Kotlin 允许使用具有可空的值的函数结构。参见[comprehensive guide to Kotlin null-safety](https://www.baeldung.com/kotlin-null-safety)。)

虽然 Java 不允许在其类型系统中表示空安全,但 Spring 框架通过在`org.springframework.lang`包中声明的对工具友好的注释提供了[null-safety of the whole Spring Framework API](core.html#null-safety)。默认情况下,来自 Kotlin 中使用的 Java API 的类型被识别为[platform types](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types),对此可以放松空值检查。[Kotlin support for JSR-305 annotations](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)和 Spring 空值注释为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全性,并具有在编译时处理`null`相关问题的优点。

|   |诸如 Reactor 或 Spring Data 之类的库提供了空安全的 API 来利用此功能。|
|---|-----------------------------------------------------------------------------------------|

你可以通过添加`-Xjsr305`编译器标志和以下选项来配置 JSR-305 检查:`-Xjsr305={strict|warn|ignore}`

对于 Kotlin 版本 1.1+,默认行为与`-Xjsr305=warn`相同。在从 Spring API 推断出的 Kotlin 类型中,`strict`值需要将 Spring FrameworkAPI 的空安全性考虑在内,但在使用该值时,应该知道 Spring API 的零性声明即使在较小的版本之间也可以发展,并且将来可能会添加更多的检查。

|   |目前还不支持泛型类型参数、varargs 和数组元素的可空性,<br/>,但应该在即将发布的版本中支持。有关最新信息,请参见[this discussion](https://github.com/Kotlin/KEEP/issues/79)。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.4.类和接口

Spring 框架支持各种 Kotlin 构造,例如通过主构造函数实例化 Kotlin 类、不可变类数据绑定和具有默认值的函数可选参数。

Kotlin 通过专用的`KotlinReflectionParameterNameDiscoverer`来识别参数名称,该参数名称允许查找接口方法参数名称,而不需要在编译过程中启用 Java8`-parameters`编译器标志。

你可以将配置类声明为[顶层或嵌套的,但不是内部的](https://kotlinlang.org/docs/reference/nested-classes.html),因为后者需要对外部类的引用。

### 1.5.注解

Spring 框架还利用[Kotlin null-safety](https://kotlinlang.org/docs/reference/null-safety.html)来确定是否需要 HTTP 参数,而无需显式地定义`required`属性。这意味着`@RequestParam name: String?`被视为不需要,相反,`@RequestParam name: String`被视为需要。 Spring 消息传递`@Header`注释上也支持此功能。

以类似的方式, Spring  Bean 带有`@Autowired``@Bean``@Inject`的注入使用该信息来确定是否需要 Bean。

例如,`@Autowired lateinit var thing: Thing`意味着必须在应用程序上下文中注册类型`Thing`的 Bean,而`@Autowired lateinit var thing: Thing?`如果不存在这样的 Bean,则不会引发错误。

遵循相同的原则,`@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)`意味着类型`Toy`的 Bean 必须在应用程序上下文中注册,而类型`Car`的 Bean 可能存在,也可能不存在。同样的行为也适用于自动连线构造函数参数。

|   |如果在具有属性或主构造函数<br/>参数的类上使用 Bean 验证,则可能需要使用[注释使用-站点目标](https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets)<br/>,例如`@field:NotNull``@get:Size(min=5, max=15)`,如[这个堆栈溢出响应](https://stackoverflow.com/a/35853200/1092077)中所述。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.6. Bean 定义 DSL

Spring Framework 支持通过使用 lambdas 作为 XML 或 Java 配置的替代方案(`@configuration``@Bean`)以功能方式注册 bean。简而言之,它允许你用 lambda 注册 bean,lambda 充当`FactoryBean`。这种机制非常有效,因为它不需要任何反射或 CGlib 代理。

例如,在 Java 中,你可以编写以下内容:

```
class Foo {}

class Bar {
    private final Foo foo;
    public Bar(Foo foo) {
        this.foo = foo;
    }
}

GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Foo.class);
context.registerBean(Bar.class, () -> new Bar(context.getBean(Foo.class)));
```

在 Kotlin 中,使用具体化的类型参数和`GenericApplicationContext` Kotlin 扩展,你可以改为编写以下内容:

```
class Foo

class Bar(private val foo: Foo)

val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean { Bar(it.getBean()) }
}
```

当类`Bar`只有一个构造函数时,你甚至可以只指定 Bean 类,构造函数参数将根据类型自动连线:

```
val context = GenericApplicationContext().apply {
    registerBean<Foo>()
    registerBean<Bar>()
}
```

为了允许更多的声明性方法和更干净的语法, Spring Framework 提供了[Kotlin bean definition DSL](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.context.support/-bean-definition-dsl/)它通过一个干净的声明性 API 声明`ApplicationContextInitializer`,它允许你处理配置文件和`Environment`,以自定义如何注册 bean。

在下面的示例中,请注意:

* 类型推理通常允许避免为 Bean 引用指定类型,如`ref("bazBean")`

* 在本例中,可以使用 Kotlin 顶级函数使用`bean(::myRouter)`之类的可调用引用来声明 bean。

* 当指定`bean<Bar>()``bean(::myRouter)`时,参数将按类型自动连线。

* 只有在`foobar`配置文件处于活动状态时,才会注册`FooBar` Bean

```
class Foo
class Bar(private val foo: Foo)
class Baz(var message: String = "")
class FooBar(private val baz: Baz)

val myBeans = beans {
    bean<Foo>()
    bean<Bar>()
    bean("bazBean") {
        Baz().apply {
            message = "Hello world"
        }
    }
    profile("foobar") {
        bean { FooBar(ref("bazBean")) }
    }
    bean(::myRouter)
}

fun myRouter(foo: Foo, bar: Bar, baz: Baz) = router {
    // ...
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|

然后,你可以使用这个`beans()`函数在应用程序上下文中注册 bean,如下例所示:

```
val context = GenericApplicationContext().apply {
    myBeans.initialize(this)
    refresh()
}
```

|   |Spring boot 是基于 javaconfig 和[does not yet provide specific support for functional bean definition](https://github.com/spring-projects/spring-boot/issues/8115)<br/>,但可以通过 Spring boot 的`ApplicationContextInitializer`支持实验性地使用函数 Bean 定义。<br/>查看[这个堆栈溢出回答](https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685)以获得更多详细信息和最新信息。另见[Spring Fu incubator](https://github.com/spring-projects/spring-fu)中开发的实验 Kofu DSL。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.7.万维网

#### 1.7.1.路由器 DSL

Spring Framework 自带的路由器 DSL 有 3 种类型:

* WebMVC.FNDSL with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.servlet.function/router.html)

* webflux.FN[Reactive](web-reactive.html#webflux-fn)dsl with[router { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/router.html)

* webflux.FN[Coroutines](#coroutines)dsl with[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)

这些 DSL 允许你编写干净且惯用的 Kotlin 代码来构建`RouterFunction`实例,如下例所示:

```
@Configuration
class RouterRouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = router {
        accept(TEXT_HTML).nest {
            GET("/") { ok().render("index") }
            GET("/sse") { ok().render("sse") }
            GET("/users", userHandler::findAllView)
        }
        "/api".nest {
            accept(APPLICATION_JSON).nest {
                GET("/users", userHandler::findAll)
            }
            accept(TEXT_EVENT_STREAM).nest {
                GET("/users", userHandler::stream)
            }
        }
        resources("/**", ClassPathResource("static/"))
    }
}
```

|   |此 DSL 是可编程的,这意味着它允许通过`if`表达式、`for`循环或任何其他 Kotlin 构造对 bean<br/>进行自定义注册逻辑。当你需要根据动态数据(例如,来自数据库)注册路由时,这可能是有用的<br/>。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

具体例子见[MiXiT project](https://github.com/mixitconf/mixit/)

#### 1.7.2.MockMVC DSL

Kotlin DSL 通过 Kotlin 扩展提供,以便提供更惯用的 Kotlin API 并允许更好的可发现性(不使用静态方法)。

```
val mockMvc: MockMvc = ...
mockMvc.get("/person/{name}", "Lee") {
    secure = true
    accept = APPLICATION_JSON
    headers {
        contentLanguage = Locale.FRANCE
    }
    principal = Principal { "foo" }
}.andExpect {
    status { isOk }
    content { contentType(APPLICATION_JSON) }
    jsonPath("$.name") { value("Lee") }
    content { json("""{"someBoolean": false}""", false) }
}.andDo {
    print()
}
```

#### 1.7.3. Kotlin 脚本模板

Spring Framework 提供了一个[“ScriptemplateView”](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/script/ScriptTemplateView.html),它支持[JSR-223](https://www.jcp.org/en/jsr/detail?id=223)通过使用脚本引擎来呈现模板。

通过利用`scripting-jsr223`依赖关系,可以使用这样的特性来呈现带有[kotlinx.html](https://github.com/Kotlin/kotlinx.html)DSL 或 Kotlin 多行插值`String`的基于 Kotlin 的模板。

`build.gradle.kts`

```
dependencies {
        runtime("org.jetbrains.kotlin:kotlin-scripting-jsr223:${kotlinVersion}")
}
```

配置通常使用`ScriptTemplateConfigurer``ScriptTemplateViewResolver`bean。

`KotlinScriptConfiguration.kt`

```
@Configuration
class KotlinScriptConfiguration {

    @Bean
    fun kotlinScriptConfigurer() = ScriptTemplateConfigurer().apply {
        engineName = "kotlin"
        setScripts("scripts/render.kts")
        renderFunction = "render"
        isSharedEngine = false
    }

    @Bean
    fun kotlinScriptViewResolver() = ScriptTemplateViewResolver().apply {
        setPrefix("templates/")
        setSuffix(".kts")
    }
}
```

有关更多详细信息,请参见[kotlin-script-templating](https://github.com/sdeleuze/kotlin-script-templating)示例项目。

#### 1.7.4. Kotlin 多平台序列化

在 Spring Framework5.3 中,[Kotlin multiplatform serialization](https://github.com/Kotlin/kotlinx.serialization)在 Spring MVC、 Spring WebFlux 和 Spring Messaging 中得到了支持。内置支持目前只针对 JSON 格式。

要启用它,请按照[那些指示](https://github.com/Kotlin/kotlinx.serialization#setup)添加相关的依赖项和插件。对于 Spring MVC 和 WebFlux,如果 Kotlin 序列化和 Jackson 都在 Classpath 中,那么它们将默认地被配置,因为 Kotlin 序列化被设计为仅序列化 Kotlin 用`@Serializable`注释的类。使用 Spring 消息传递,如果你想要自动配置,则确保 Jackson、GSON 或 JSONB 都不在 Classpath 中,如果需要配置 Jackson,则手动配置`KotlinSerializationJsonMessageConverter`

### 1.8.协理

Kotlin [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)是 Kotlin 轻量级线程,允许以强制方式编写非阻塞代码。在语言端,挂起函数为异步操作提供了抽象,而在库端[Kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines)提供了[`async { }`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html)之类的函数和[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)之类的类型。

Spring 框架在以下范围上为协程提供支持:

* [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)[Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)返回 Spring MVC 和 WebFlux 中支持的值,注释`@Controller`

* Spring MVC 和 WebFlux 注释`@Controller`中的挂起功能支持

* WebFlux[client](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.client/index.html)[server](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/index.html)函数 API 的扩展。

* WebFlux.FN[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL

* 挂起函数和`Flow`在 RSocket 中支持`@MessageMapping`注释方法

* [rsocketrequester’](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.messaging.rsocket/index.html)的扩展

#### 1.8.1.依赖关系

`kotlinx-coroutines-core``kotlinx-coroutines-reactor`依赖项位于 Classpath 中时,将启用协程支持:

`build.gradle.kts`

```
dependencies {

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}")
}
```

支持`1.4.0`及以上版本。

#### 1.8.2.反应性如何转化为协程?

对于返回值,从 Active 到 CoroutineAPI 的转换如下:

* `fun handler(): Mono<Void>`变为`suspend fun handler()`

* `fun handler(): Mono<T>`变为`suspend fun handler(): T``suspend fun handler(): T?`取决于`Mono`是否为空(具有更静态类型的优点)

* `fun handler(): Flux<T>`变为`fun handler(): Flow<T>`

输入参数:

* 如果不需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(value: T)`,因为可以调用挂起的函数来获得值参数。

* 如果需要惰性,则`fun handler(mono: Mono<T>)`变为`fun handler(supplier: suspend () → T)``fun handler(supplier: suspend () → T?)`

[`Flow`](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)在协程世界中是`Flux`等价的,适用于冷热气流、有限气流或无限气流,有以下主要区别:

* `Flow`是推拉式的,而`Flux`是推拉式的混合动力

* 背压是通过悬挂功能实现的。

* `Flow`只有一个[single suspending `collect` method](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/collect.html),运算符实现为[extensions](https://kotlinlang.org/docs/reference/extensions.html)

* [运营商很容易实现。](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common/src/flow/operators)感谢协程

* 扩展允许将自定义运算符添加到`Flow`

* 收集操作是挂起的功能

* [`map` operator](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html)支持异步操作(不需要`flatMap`),因为它需要一个挂起的函数参数

阅读这篇关于[Going Reactive with Spring, Coroutines and Kotlin Flow](https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow)的博客文章,了解更多详细信息,包括如何与协程同时运行代码。

#### 1.8.3.控制器

下面是一个协程`@RestController`的例子。

```
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {

    @GetMapping("/suspend")
    suspend fun suspendingEndpoint(): Banner {
        delay(10)
        return banner
    }

    @GetMapping("/flow")
    fun flowEndpoint() = flow {
        delay(10)
        emit(banner)
        delay(10)
        emit(banner)
    }

    @GetMapping("/deferred")
    fun deferredEndpoint() = GlobalScope.async {
        delay(10)
        banner
    }

    @GetMapping("/sequential")
    suspend fun sequential(): List<Banner> {
        val banner1 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        val banner2 = client
                .get()
                .uri("/suspend")
                .accept(MediaType.APPLICATION_JSON)
                .awaitExchange()
                .awaitBody<Banner>()
        return listOf(banner1, banner2)
    }

    @GetMapping("/parallel")
    suspend fun parallel(): List<Banner> = coroutineScope {
        val deferredBanner1: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        val deferredBanner2: Deferred<Banner> = async {
            client
                    .get()
                    .uri("/suspend")
                    .accept(MediaType.APPLICATION_JSON)
                    .awaitExchange()
                    .awaitBody<Banner>()
        }
        listOf(deferredBanner1.await(), deferredBanner2.await())
    }

    @GetMapping("/error")
    suspend fun error() {
        throw IllegalStateException()
    }

    @GetMapping("/cancel")
    suspend fun cancel() {
        throw CancellationException()
    }

}
```

还支持`@Controller`的视图呈现。

```
@Controller
class CoroutinesViewController(banner: Banner) {

    @GetMapping("/")
    suspend fun render(model: Model): String {
        delay(10)
        model["banner"] = banner
        return "index"
    }
}
```

#### 1.8.4.WebFlux.FN

下面是通过[coRouter { }](https://docs.spring.io/spring-framework/docs/5.3.16/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/co-router.html)DSL 和相关处理程序定义的协程路由器的示例。

```
@Configuration
class RouterConfiguration {

    @Bean
    fun mainRouter(userHandler: UserHandler) = coRouter {
        GET("/", userHandler::listView)
        GET("/api/user", userHandler::listApi)
    }
}
```

```
class UserHandler(builder: WebClient.Builder) {

    private val client = builder.baseUrl("...").build()

    suspend fun listView(request: ServerRequest): ServerResponse =
            ServerResponse.ok().renderAndAwait("users", mapOf("users" to
            client.get().uri("...").awaitExchange().awaitBody<User>()))

    suspend fun listApi(request: ServerRequest): ServerResponse =
                ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
                client.get().uri("...").awaitExchange().awaitBody<User>())
}
```

#### 1.8.5.交易

通过 Spring 框架 5.2 提供的反应式事务管理的编程变体,支持协程上的事务。

对于挂起的函数,提供了`TransactionalOperator.executeAndAwait`扩展。

```
import org.springframework.transaction.reactive.executeAndAwait

class PersonRepository(private val operator: TransactionalOperator) {

    suspend fun initDatabase() = operator.executeAndAwait {
        insertPerson1()
        insertPerson2()
    }

    private suspend fun insertPerson1() {
        // INSERT SQL statement
    }

    private suspend fun insertPerson2() {
        // INSERT SQL statement
    }
}
```

对于 Kotlin `Flow`,提供了一个`Flow<T>.transactional`扩展。

```
import org.springframework.transaction.reactive.transactional

class PersonRepository(private val operator: TransactionalOperator) {

    fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)

    private fun findPeople(): Flow<Person> {
        // SELECT SQL statement
    }

    private suspend fun updatePerson(person: Person): Person {
        // UPDATE SQL statement
    }
}
```

### 1.9. Spring  Kotlin 中的项目

本节提供了一些值得在 Kotlin 中开发 Spring 项目的具体提示和建议。

#### 1.9.1.默认情况下为 final

默认情况下,[all classes in Kotlin are `final`](https://discuss.kotlinlang.org/t/classes-final-by-default/166)。类上的`open`修饰符与 Java 的`final`相反:它允许其他人继承这个类。这也适用于成员函数,因为它们需要标记为`open`才能被重写。

虽然 Kotlin 的 JVM 友好设计通常与 Spring 无摩擦,但如果不考虑这一事实,则此特定的 Kotlin 特性可以阻止应用程序启动。这是因为 Spring bean(例如`@Configuration`注释类,由于技术原因,默认情况下需要在运行时进行扩展)通常是由 CGLIB 代理的。解决方法是在 Spring bean 的每个类和成员函数上添加一个`open`关键字,这些类和成员函数是由 CGlib 代理的,这可能很快会变得很痛苦,并且违反 Kotlin 保持代码简洁和可预测的原则。

|   |也可以通过使用`@Configuration(proxyBeanMethods = false)`来避免配置类的 CGLIB 代理。<br/>查看[“ProxyBeanMethods”Javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html#proxyBeanMethods--)以获得更多详细信息。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

幸运的是, Kotlin 提供了一个[`kotlin-spring`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin)插件(`kotlin-allopen`插件的预先配置版本),该插件自动为使用以下注释之一进行注释或元注释的类型打开类及其成员函数:

* `@Component`

* `@Async`

* `@Transactional`

* `@Cacheable`

元注释支持意味着使用`@Configuration``@Controller`、<restcontroller`、或`@Repository`进行注释的类型将自动打开,因为这些注释是用`@Component`进行元注释的。

[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)默认情况下启用`kotlin-spring`插件。因此,在实践中,你可以在不添加任何`open`关键字的情况下编写 Kotlin bean,就像在 Java 中一样。

|   |Spring 框架文档中的 Kotlin 代码示例并未在类及其成员函数上明确指定“open”。示例是使用`kotlin-allopen`插件为<br/>项目编写的,因为这是最常用的设置。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.2.使用不可变类实例实现持久性

在 Kotlin 中,在主构造函数中声明只读属性是很方便的,并且被认为是一种最佳实践,如下例所示:

```
class Person(val name: String, val age: Int)
```

你可以选择添加[the `data` keyword](https://kotlinlang.org/docs/reference/data-classes.html),以使编译器自动从主构造函数中声明的所有属性派生出以下成员:

* `equals()`和`hashCode()`

* `toString()`的形式`"User(name=John, age=42)"`

* `componentN()`与其声明顺序中的属性对应的函数

* `copy()`函数

正如下面的示例所示,这允许对单个属性进行简单的更改,即使`Person`属性是只读的:

```
data class Person(val name: String, val age: Int)

val jack = Person(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
```

常见的持久性技术(例如 JPA)需要一个默认的构造函数,从而阻止了这种设计。幸运的是,对于这个[“默认构造函数地狱”](https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell)有一种解决方法,因为 Kotlin 提供了一个[`kotlin-jpa`](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-jpa-compiler-plugin)插件,该插件为带有 JPA 注释的类生成合成的无 arg 构造函数。

如果需要为其他持久性技术利用这种机制,可以配置[`kotlin-noarg`](https://kotlinlang.org/docs/reference/compiler-plugins.html#how-to-use-no-arg-plugin)插件。

|   |在 Kay Release Train 中, Spring 数据支持 Kotlin 不可变类实例,并且如果模块使用 Spring 数据对象映射`kotlin-noarg`(例如 MongoDB、Redis、Cassandra 和其他),则`kotlin-noarg`不需要<gt r=“261”插件。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.3.注入依赖项

我们的建议是尝试使用`val`只读(并且在可能的情况下不可为空)[properties](https://kotlinlang.org/docs/reference/properties.html)的构造函数注入,如下例所示:

```
@Component
class YourBean(
    private val mongoTemplate: MongoTemplate,
    private val solrClient: SolrClient
)
```

|   |带有单个构造函数的类的参数自动自动连线。<br/>这就是为什么在上面的`@Autowired constructor`示例中不需要显式的`@Autowired constructor`的原因。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果确实需要使用字段注入,可以使用`lateinit var`构造,如下例所示:

```
@Component
class YourBean {

    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    @Autowired
    lateinit var solrClient: SolrClient
}
```

#### 1.9.4.注入配置属性

是用于[字符串插值](https://kotlinlang.org/docs/reference/idioms.html#string-interpolation)的保留字符。

字符。

|   |如果使用 Spring boot,则可能应该使用[@configrationProperties](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties)而不是`@Value`注释。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

作为一种选择,你可以通过声明以下配置 bean 来定制属性占位符前缀:

```
@Bean
fun propertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
    setPlaceholderPrefix("%{")
}
```

你可以使用配置 bean 自定义使用`${…​}`语法的现有代码(例如 Spring 引导执行器或`@LocalServerPort`),如下例所示:

```
@Bean
fun kotlinPropertyConfigurer() = PropertySourcesPlaceholderConfigurer().apply {
    setPlaceholderPrefix("%{")
    setIgnoreUnresolvablePlaceholders(true)
}

@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
```

#### 1.9.5.已检查的异常

Java 和[Kotlin exception handling](https://kotlinlang.org/docs/reference/exceptions.html)非常接近,主要区别在于 Kotlin 将所有异常都视为未经检查的异常。但是,当使用代理对象(例如,用`@Transactional`注释的类或方法)时,抛出的选中异常将默认包装在`UndeclaredThrowableException`中。

要像在 Java 中一样获得原始抛出的异常,应该使用[`@Throws`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-throws/index.html)对方法进行注释,以显式地指定抛出的检查过的异常(例如`@Throws(IOException::class)`)。

#### 1.9.6.注释数组属性

Kotlin 注释大多类似于 Java 注释,但是数组属性(在 Spring 中广泛使用)的行为是不同的。正如在[Kotlin documentation](https://kotlinlang.org/docs/reference/annotations.html)中所解释的,与其他属性不同,你可以省略`value`属性名称,并将其指定为`vararg`参数。

要理解这意味着什么,可以将`@RequestMapping`(这是使用最广泛的 Spring 注释之一)作为示例。此 Java 注释声明如下:

```
public @interface RequestMapping {

    @AliasFor("path")
    String[] value() default {};

    @AliasFor("value")
    String[] path() default {};

    RequestMethod[] method() default {};

    // ...
}
```

`@RequestMapping`的典型用例是将处理程序方法映射到特定的路径和方法。在 Java 中,你可以为 Annotation Array 属性指定一个值,然后将其自动转换为一个数组。

这就是为什么我们可以写“@requestmapping(value=“/toys”,method=requestmethod.get)”或“@requestmapping(path=“/toys”,method=requestmethod.get)”。

但是,在 Kotlin 中,你必须写`@RequestMapping("/toys", method = [RequestMethod.GET])`或`@RequestMapping(path = ["/toys"], method = [RequestMethod.GET])`(需要用命名的数组属性指定方括号)。

对于这个特定的`method`属性(最常见的一种),另一种选择是使用快捷方式注释,例如`@GetMapping`,`@PostMapping`等。

|   |如果`@RequestMapping``method`属性未指定,则所有 HTTP 方法都将<br/>进行匹配,而不仅仅是`GET`方法。|
|---|------------------------------------------------------------------------------------------------------------------------------|

#### 1.9.7.测试

本节讨论使用 Kotlin 和 Spring 框架的组合进行的测试。推荐的测试框架是[JUnit 5](https://junit.org/junit5/)以及用于模拟的[Mockk](https://mockk.io/)。

|   |如果你正在使用 Spring 引导,请参见[这个相关的文档](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-kotlin-testing)。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------|

##### 构造函数注入

正如在[专用部分](testing.html#testcontext-junit-jupiter-di#spring-web-reactive)中所描述的,JUnit5 允许构造函数注入 bean,这在 Kotlin 中非常有用,以便使用`val`而不是`lateinit var`。你可以使用[@TestConstructor](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestConstructor.html)为所有参数启用自动布线。

```
@SpringJUnitConfig(TestConfig::class)
@TestConstructor(autowireMode = AutowireMode.ALL)
class OrderServiceIntegrationTests(val orderService: OrderService,
                                   val customerService: CustomerService) {

    // tests that use the injected OrderService and CustomerService
}
```

##### `PER_CLASS`生命周期

Kotlin 允许你在 backticks 之间指定有意义的测试函数名。在 JUnit5 中, Kotlin 测试类可以使用`@TestInstance(TestInstance.Lifecycle.PER_CLASS)`注释来启用测试类的单实例,这允许在非静态方法上使用`@BeforeAll`和`@AfterAll`注释,这很好地适合 Kotlin。

你还可以将默认行为更改为`PER_CLASS`,这要感谢带有`junit-platform.properties`属性的`junit.jupiter.testinstance.lifecycle.default = per_class`文件。

下面的示例演示了关于非静态方法的`@BeforeAll`和`@AfterAll`注释:

```
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class IntegrationTests {

  val application = Application(8181)
  val client = WebClient.create("http://localhost:8181")

  @BeforeAll
  fun beforeAll() {
    application.start()
  }

  @Test
  fun `Find all users on HTML page`() {
    client.get().uri("/users")
        .accept(TEXT_HTML)
        .retrieve()
        .bodyToMono<String>()
        .test()
        .expectNextMatches { it.contains("Foo") }
        .verifyComplete()
  }

  @AfterAll
  fun afterAll() {
    application.stop()
  }
}
```

##### 类似规范的测试

你可以使用 JUnit5 和 Kotlin 创建类似于规范的测试。下面的示例展示了如何做到这一点:

```
class SpecificationLikeTests {

  @Nested
  @DisplayName("a calculator")
  inner class Calculator {
     val calculator = SampleCalculator()

     @Test
     fun `should return the result of adding the first number to the second number`() {
        val sum = calculator.sum(2, 4)
        assertEquals(6, sum)
     }

     @Test
     fun `should return the result of subtracting the second number from the first number`() {
        val subtract = calculator.subtract(4, 2)
        assertEquals(2, subtract)
     }
  }
}
```

##### `WebTestClient` Kotlin 中的类型推断问题

由于[类型推断问题](https://youtrack.jetbrains.com/issue/KT-5464),你必须使用 Kotlin `expectBody`扩展(例如`.expectBody<String>().isEqualTo("toys")`),因为它为 Java API 的 Kotlin 问题提供了解决方法。

另见相关的[SPR-16057](https://jira.spring.io/browse/SPR-16057)问题。

### 1.10.开始

学习如何使用 Kotlin 构建 Spring 应用程序的最简单的方法是遵循[专门的教程](https://spring.io/guides/tutorials/spring-boot-kotlin/)。

#### 1.10.1.`start.spring.io`

在 Kotlin 中启动新 Spring 框架项目的最简单的方法是在[start.spring.io](https://start.spring.io/#!language=kotlin&type=gradle-project)上创建新的 Spring Boot2 项目。

#### 1.10.2.选择网络口味

Spring Framework 现在带有两个不同的 Web 栈:[Spring MVC](web.html#mvc)和[Spring WebFlux](web-reactive.html#spring-web-reactive)。

Spring 如果你希望创建将处理延迟、长寿命连接、流场景的应用程序,或者如果你希望使用具有 Web 功能的 DSL,则建议使用 WebFlux Kotlin。

对于其他用例,特别是如果正在使用诸如 JPA 这样的阻塞技术, Spring MVC 及其基于注释的编程模型是推荐的选择。

### 1.11.资源

我们向学习如何使用 Kotlin 和 Spring 框架构建应用程序的人们推荐以下资源:

* [Kotlin language reference](https://kotlinlang.org/docs/reference/)

* [Kotlin Slack](https://slack.kotlinlang.org/)(带专用 # Spring 频道)

* [Stackoverflow, with `spring` and `kotlin` tags](https://stackoverflow.com/questions/tagged/spring+kotlin)

* [Try Kotlin in your browser](https://play.kotlinlang.org/)

* [Kotlin blog](https://blog.jetbrains.com/kotlin/)

* [Awesome Kotlin](https://kotlin.link/)

#### 1.11.1.例子

以下 GitHub 项目提供了你可以学习甚至扩展的示例:

* [spring-boot-kotlin-demo](https://github.com/sdeleuze/spring-boot-kotlin-demo):常规 Spring 引导和 Spring 数据 JPA 项目

* [mixit](https://github.com/mixitconf/mixit): Spring Boot2,WebFlux,和 Reactive Spring Data MongoDB

* [spring-kotlin-functional](https://github.com/sdeleuze/spring-kotlin-functional):独立的 WebFlux 和 Functional Bean 定义 DSL

* [spring-kotlin-fullstack](https://github.com/sdeleuze/spring-kotlin-fullstack):使用 Kotlin2js 代替 JavaScript 或 TypeScript 作为前端的 webflux Kotlin fullstack 示例

* [spring-petclinic-kotlin](https://github.com/spring-petclinic/spring-petclinic-kotlin): Spring PetClinic 样本申请的 Kotlin 版本

* [spring-kotlin-deepdive](https://github.com/sdeleuze/spring-kotlin-deepdive):引导 1.0 和 Java 到引导 2.0 和 Kotlin 的逐步迁移指南

* [spring-cloud-gcp-kotlin-app-sample](https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-kotlin-samples/spring-cloud-gcp-kotlin-app-sample): Spring 启动与谷歌云平台集成

#### 1.11.2.问题

以下清单对与 Spring 和 Kotlin 支持有关的未决问题进行了分类:

* Spring Framework

  * [Unable to use WebTestClient with mock server in Kotlin](https://github.com/spring-projects/spring-framework/issues/20606)

  * [在泛型、变量和数组元素级别支持零安全](https://github.com/spring-projects/spring-framework/issues/20496)

* Kotlin

  * [Parent issue for Spring Framework support](https://youtrack.jetbrains.com/issue/KT-6380)

  * [Kotlin requires type inference where Java doesn’t](https://youtrack.jetbrains.com/issue/KT-5464)

  * [具有开放类的智能强制回归](https://youtrack.jetbrains.com/issue/KT-20283)

  * [不可能传递不是所有的 SAM 参数作为函数](https://youtrack.jetbrains.com/issue/KT-14984)

  * [通过脚本变量直接支持 JSR223 绑定](https://youtrack.jetbrains.com/issue/KT-15125)

  * [Kotlin properties do not override Java-style getters and setters](https://youtrack.jetbrains.com/issue/KT-6653)

## 2. Apache Groovy

Groovy 是一种功能强大的、可选类型的动态语言,具有静态类型和静态编译功能。它提供了简洁的语法,并与任何现有的 Java 应用程序平滑地集成在一起。

Spring 框架提供了一个专用的`ApplicationContext`,该框架支持基于 Groovy Bean 定义的 DSL。有关更多详细信息,请参见[The Groovy Bean Definition DSL](core.html#groovy-bean-definition-dsl)。

对 Groovy 的进一步支持,包括用 Groovy 编写的 bean、可刷新的脚本 bean,以及[动态语言支持](#dynamic-language)中提供的更多支持。

## 3. 动态语言支持

Spring 为使用已经通过使用动态语言(例如 Groovy)定义的类和对象提供了全面的支持。这种支持使你能够在受支持的动态语言中编写任意数量的类,并让 Spring 容器透明地实例化、配置和依赖注入结果对象。

Spring 的脚本支持主要针对 Groovy 和 BeanShell。除了那些特别支持的语言之外,JSR-223 脚本机制还支持与任何具有 JSR-223 功能的语言提供程序的集成(从 Spring 4.2 开始),例如 JRuby。

你可以在[Scenarios](#dynamic-language-scenarios)中找到充分工作的示例,说明这种动态语言支持可以立即发挥作用。

### 3.1.第一个例子

本章的主要内容是详细描述动态语言支持。在深入研究动态语言支持的所有细节和细节之前,我们先看一个在动态语言中定义的 Bean 的快速示例。这第一个 Bean 的动态语言是 Groovy。(这个示例的基础取自 Spring 测试套件。如果你想在任何其他受支持的语言中看到等效的示例,请查看源代码)。

下一个示例显示了 Groovy Bean 将要实现的`Messenger`接口。请注意,这个接口是用纯 Java 定义的。通过引用`Messenger`注入的依赖对象不知道底层实现是 Groovy 脚本。下面的清单显示了`Messenger`接口:

```
package org.springframework.scripting;

public interface Messenger {

    String getMessage();
}
```

下面的示例定义了一个对`Messenger`接口具有依赖关系的类:

```
package org.springframework.scripting;

public class DefaultBookingService implements BookingService {

    private Messenger messenger;

    public void setMessenger(Messenger messenger) {
        this.messenger = messenger;
    }

    public void processBooking() {
        // use the injected Messenger object...
    }
}
```

下面的示例在 Groovy 中实现了`Messenger`接口:

```
// from the file 'Messenger.groovy'
package org.springframework.scripting.groovy;

// import the Messenger interface (written in Java) that is to be implemented
import org.springframework.scripting.Messenger

// define the implementation in Groovy
class GroovyMessenger implements Messenger {

    String message
}
```

|   |要使用自定义的动态语言标记来定义动态语言支持的 bean,你需要在 Spring XML 配置文件的顶部具有 XML 模式序言。<br/>还需要使用 Spring `ApplicationContext`实现作为你的 IOC<br/>容器。支持使用带有普通`BeanFactory`实现的动态语言支持的 bean,但是你必须管理 Spring 内部<br/>的管道才能这样做。<br/><br/>有关基于模式的配置的更多信息,请参见[基于 XML 模式的配置](#xsd-schemas-lang)。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

最后,下面的示例展示了 Bean 定义,这些定义会将 Groovy 定义的`Messenger`实现注入到“DefaultBookingService”类的实例中:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">

    <!-- this is the bean definition for the Groovy-backed Messenger implementation -->
    <lang:groovy id="messenger" script-source="classpath:Messenger.groovy">
        <lang:property name="message" value="I Can Do The Frug" />
    </lang:groovy>

    <!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger -->
    <bean id="bookingService" class="x.y.DefaultBookingService">
        <property name="messenger" ref="messenger" />
    </bean>

</beans>
```

`bookingService` Bean(a`DefaultBookingService`)现在可以正常使用其私有`messenger`成员变量,因为注入到它的`Messenger`实例是`Messenger`实例。这里没有什么特别的——只有普通的 Java 和普通的 Groovy。

希望前面的 XML 片段是不言自明的,但如果不是,也不要过分担心。继续阅读关于前面配置的原因和原因的深入细节。

### 3.2.定义由动态语言支持的 bean

本节详细描述了如何在任何受支持的动态语言中定义 Spring-managed bean。

请注意,本章并不试图解释所支持的动态语言的语法和习语。例如,如果你想使用 Groovy 在应用程序中编写某些类,我们假设你已经了解 Groovy。如果你需要更多关于动态语言本身的详细信息,请参阅本章末尾的[更多资源](#dynamic-language-resources)。

#### 3.2.1.共同概念

使用支持动态语言的 bean 所涉及的步骤如下:

1. 为动态语言编写测试源代码(自然).

2. 然后编写动态语言的源代码本身.

3. 通过在 XML 配置中使用适当的`<lang:language/>`元素来定义你的动态语言支持的 bean(你可以通过使用 Spring API 以编程方式定义这样的 bean,尽管你将不得不查询源代码以了解如何做到这一点,因为本章不涉及这种类型的高级配置)。请注意,这是一个迭代步骤。对于每个动态语言源文件,至少需要一个 Bean 定义(尽管多个 Bean 定义可以引用相同的源文件)。

前两个步骤(测试和编写动态语言源文件)超出了本章的范围。请参阅你所选择的动态语言的语言规范和参考手册,并继续开发你的动态语言源文件。不过,你首先想阅读本章的其余部分,因为 Spring 的动态语言支持确实对动态语言源文件的内容进行了一些(小)假设。

##### \<lang:language/\>元素

在[前一节](#dynamic-language-beans-concepts)列表中的最后一步涉及定义动态语言支持的 Bean 定义,对于每个要配置的 Bean 定义一个(这与普通的 JavaBean 配置没有什么不同)。但是,你可以使用`<lang:language/>`元素来定义支持动态语言的 Bean,而不是指定要由容器实例化和配置的类的完全限定类名称。

每个受支持的语言都有一个对应的`<lang:language/>`元素:

* `<lang:groovy/>`

* `<lang:bsh/>`

* `<lang:std/>`(JSR-223,例如使用 JRuby)

可用于配置的确切属性和子元素取决于 Bean 在哪种语言中定义的准确(本章后面的语言特定部分详细介绍了这一点)。

##### 可刷新的咖啡豆

Spring 中动态语言支持的最引人注目的增值之一(或许也是唯一的)是“可刷新 Bean”特性。

可刷新的 Bean 是动态语言支持的 Bean。 Bean 通过少量配置,支持动态语言的动态文件可以监视其底层源文件资源中的更改,然后在动态语言源文件发生更改时重新加载自身(例如,当你编辑和保存对文件系统上的文件的更改时)。

这使你能够将任意数量的动态语言源文件部署为应用程序的一部分,配置 Spring 容器以创建由动态语言源文件支持的 bean(使用本章中描述的机制),以及(稍后, Bean 随着需求的变化或其他一些外部因素起作用),编辑动态语言源文件,并将它们所做的任何更改反映在由所更改的动态语言源文件支持的 Bean 中。没有必要关闭正在运行的应用程序(或者在 Web 应用程序的情况下重新部署)。 Bean 修改后的动态语言支持的 Bean 从更改后的动态语言源文件中获取新的状态和逻辑。

|   |默认情况下,此功能是关闭的。|
|---|-------------------------------|

现在,我们可以看看一个示例,看看开始使用可刷新 bean 是多么容易。要打开可刷新的 bean 特性,你必须在 Bean 定义的`<lang:language/>`元素上精确地指定一个附加属性。因此,如果我们坚持使用本章前面的[the example](#dynamic-language-a-first-example),下面的示例展示了我们将在 Spring XML 配置中进行哪些更改以实现可刷新的 bean:

```
<beans>

    <!-- this bean is now 'refreshable' due to the presence of the 'refresh-check-delay' attribute -->
    <lang:groovy id="messenger"
            refresh-check-delay="5000" <!-- switches refreshing on with 5 seconds between checks -->
            script-source="classpath:Messenger.groovy">
        <lang:property name="message" value="I Can Do The Frug" />
    </lang:groovy>

    <bean id="bookingService" class="x.y.DefaultBookingService">
        <property name="messenger" ref="messenger" />
    </bean>

</beans>
```

这真的是你所要做的一切。在“Messenger” Bean 定义中定义的`refresh-check-delay`属性是对底层动态语言源文件进行任何更改后刷新 Bean 的毫秒数。你可以通过为“刷新-检查-延迟”属性分配一个负值来关闭刷新行为。请记住,默认情况下,刷新行为是禁用的。如果不想要刷新行为,请不要定义属性。

如果我们接着运行下面的应用程序,我们就可以使用这个可刷新的特性。(请原谅下一段代码中的“跳过环到暂停执行”的恶作剧。)`System.in.read()`调用仅存在于此,以便当你(此场景中的开发人员)关闭并编辑底层动态语言源文件时,程序的执行暂停当程序恢复执行时,在动态语言支持的 Bean 上触发刷新。

下面的清单显示了这个示例应用程序:

```
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;

public final class Boot {

    public static void main(final String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Messenger messenger = (Messenger) ctx.getBean("messenger");
        System.out.println(messenger.getMessage());
        // pause execution while I go off and make changes to the source file...
        System.in.read();
        System.out.println(messenger.getMessage());
    }
}
```

然后,为了本例的目的,假设对`Messenger`方法的所有调用都必须进行更改,以便消息被引号包围。下面的清单显示了在暂停执行程序时,你(开发人员)应该对`Messenger.groovy`源文件进行的更改:

```
package org.springframework.scripting

class GroovyMessenger implements Messenger {

    private String message = "Bingo"

    public String getMessage() {
        // change the implementation to surround the message in quotes
        return "'" + this.message + "'"
    }

    public void setMessage(String message) {
        this.message = message
    }
}
```

当程序运行时,输入暂停前的输出将是`I Can Do The Frug`。在对源文件进行更改并将其保存并且程序恢复执行之后,在动态语言支持的 `Messenger’实现上调用`getMessage()`方法的结果是`'I Can Do The Frug'`(请注意,其中包含了附加的引号)。

如果对脚本的更改发生在`refresh-check-delay`值的窗口内,则不会触发刷新。 Bean 在调用支持动态语言的方法之前,实际上不会接收到对脚本的更改。 Bean 只有当在支持动态语言的方法上调用方法时,它才会检查其底层脚本源是否已更改。与刷新脚本有关的任何异常(例如遇到编译错误或发现脚本文件已被删除)都会导致将致命异常传播到调用代码中。

Bean 前面描述的可刷新行为不适用于使用`<lang:inline-script/>`元素符号定义的动态语言源文件(参见[内联动态语言源文件](#dynamic-language-beans-inline))。此外,它仅适用于实际可以检测到对基础源文件的更改的 bean(例如,通过检查文件系统上存在的动态语言源文件的最后修改日期的代码)。

##### 内联动态语言源文件

动态语言支持还可以迎合直接嵌入在 Spring  Bean 定义中的动态语言源文件。更具体地说,`<lang:inline-script/>` 元素允许你在 Spring 配置文件中立即定义动态语言源。一个示例可能会说明内联脚本功能是如何工作的:

```
<lang:groovy id="messenger">
    <lang:inline-script>

package org.springframework.scripting.groovy;

import org.springframework.scripting.Messenger

class GroovyMessenger implements Messenger {
    String message
}

    </lang:inline-script>
    <lang:property name="message" value="I Can Do The Frug" />
</lang:groovy>
```

如果我们不去考虑在 Spring 配置文件中定义动态语言源是否是一种好的实践的问题,`<lang:inline-script/>`元素在某些场景中可能是有用的。例如,我们可能希望快速地将 Spring `Validator`实现添加到 Spring MVC`Controller`中。这只是一个时刻的工作,使用内联资源。(例如,见[脚本验证器](#dynamic-language-scenarios-validators)。

##### 在支持动态语言的 bean 上下文中理解构造函数注入

关于 Spring 的动态语言支持,有一件非常重要的事情需要注意。也就是说,你不能(当前)向支持动态语言的 bean 提供构造函数参数(因此,对于支持动态语言的 bean,构造函数注入是不可用的)。为了使构造函数和属性的这种特殊处理 100% 清晰,以下代码和配置的混合不起作用:

一种行不通的方法

```
// from the file 'Messenger.groovy'
package org.springframework.scripting.groovy;

import org.springframework.scripting.Messenger

class GroovyMessenger implements Messenger {

    GroovyMessenger() {}

    // this constructor is not available for Constructor Injection
    GroovyMessenger(String message) {
        this.message = message;
    }

    String message

    String anotherMessage
}
```

```
<lang:groovy id="badMessenger"
    script-source="classpath:Messenger.groovy">
    <!-- this next constructor argument will not be injected into the GroovyMessenger -->
    <!-- in fact, this isn't even allowed according to the schema -->
    <constructor-arg value="This will not work" />

    <!-- only property values are injected into the dynamic-language-backed object -->
    <lang:property name="anotherMessage" value="Passed straight through to the dynamic-language-backed object" />

</lang>
```

在实践中,这种限制并不像最初出现的那样重要,因为 Setter 注入是绝大多数开发人员所青睐的注入风格(关于这是否是一件好事的讨论,我们将留待以后讨论)。

#### 3.2.2.groovy beans

本节描述如何使用 Spring 中在 Groovy 中定义的 bean。

Groovy 主页包括以下描述:

Groovy 是一种面向 Java2 平台的敏捷动态语言,它具有许多人们非常喜欢的 Python、Ruby 和 Smalltalk 等语言的特性,使 Java 开发人员可以使用类似 Java 的语法来使用这些特性。”

如果你直接从顶部阅读了这一章,那么你已经获得了支持 Groovy-Dynamic-Language 的[seen an example](#dynamic-language-a-first-example) Bean。现在考虑另一个示例(再次使用 Spring 测试套件中的示例):

```
package org.springframework.scripting;

public interface Calculator {

    int add(int x, int y);
}
```

下面的示例在 Groovy 中实现了`Calculator`接口:

```
// from the file 'calculator.groovy'
package org.springframework.scripting.groovy

class GroovyCalculator implements Calculator {

    int add(int x, int y) {
        x + y
    }
}
```

Bean 以下定义使用了在 Groovy 中定义的计算器:

```
<!-- from the file 'beans.xml' -->
<beans>
    <lang:groovy id="calculator" script-source="classpath:calculator.groovy"/>
</beans>
```

最后,下面的小应用程序执行前面的配置:

```
package org.springframework.scripting;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Calculator calc = ctx.getBean("calculator", Calculator.class);
        System.out.println(calc.add(2, 8));
    }
}
```

运行上述程序的结果输出是(不出所料)`10`。(有关更多有趣的示例,请参见 Dynamic Language Showcase 项目,以获得更复杂的示例,或者参见本章后面的示例[Scenarios](#dynamic-language-scenarios))。

每个 Groovy 源文件不能定义多个类。虽然这在 Groovy 中完全合法,但(可以说)这是一种糟糕的做法。为了采用一致的方法,你应该(在 Spring 团队的意见中)尊重每个源文件一个(公共)类的标准 Java 约定。

##### 通过使用回调自定义 Groovy 对象

Bean `GroovyObjectCustomizer`接口是一个回调,它允许你将额外的创建逻辑连接到创建支持 Groovy 的过程中。例如,该接口的实现可以调用任何必需的初始化方法,设置一些默认属性值,或者指定一个自定义`MetaClass`。下面的清单显示了`GroovyObjectCustomizer`接口定义:

```
public interface GroovyObjectCustomizer {

    void customize(GroovyObject goo);
}
```

Spring 框架实例化支持 Groovy 的 Bean 的实例,然后将创建的`GroovyObject`传递给指定的`GroovyObjectCustomizer`(如果已经定义了一个)。你可以使用提供的`GroovyObject`引用执行任何你喜欢的操作。我们预计大多数人都希望通过这个回调设置一个自定义`MetaClass`,下面的示例展示了如何这样做:

```
public final class SimpleMethodTracingCustomizer implements GroovyObjectCustomizer {

    public void customize(GroovyObject goo) {
        DelegatingMetaClass metaClass = new DelegatingMetaClass(goo.getMetaClass()) {

            public Object invokeMethod(Object object, String methodName, Object[] arguments) {
                System.out.println("Invoking '" + methodName + "'.");
                return super.invokeMethod(object, methodName, arguments);
            }
        };
        metaClass.initialize();
        goo.setMetaClass(metaClass);
    }

}
```

在 Groovy 中对元编程的全面讨论超出了 Spring 参考手册的范围。请参阅 Groovy 参考手册的相关部分或在线搜索。很多文章都谈到了这个话题。实际上,如果使用 Spring 名称空间支持,那么使用“GroovyObjectCustomizer”很容易,如下例所示:

```
<!-- define the GroovyObjectCustomizer just like any other bean -->
<bean id="tracingCustomizer" class="example.SimpleMethodTracingCustomizer"/>

    <!-- ... and plug it into the desired Groovy bean via the 'customizer-ref' attribute -->
    <lang:groovy id="calculator"
        script-source="classpath:org/springframework/scripting/groovy/Calculator.groovy"
        customizer-ref="tracingCustomizer"/>
```

如果不使用 Spring 名称空间支持,你仍然可以使用“GroovyObjectCustomizer”功能,如下例所示:

```
<bean id="calculator" class="org.springframework.scripting.groovy.GroovyScriptFactory">
    <constructor-arg value="classpath:org/springframework/scripting/groovy/Calculator.groovy"/>
    <!-- define the GroovyObjectCustomizer (as an inner bean) -->
    <constructor-arg>
        <bean id="tracingCustomizer" class="example.SimpleMethodTracingCustomizer"/>
    </constructor-arg>
</bean>

<bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/>
```

|   |你还可以在 Spring 的“GroovyObjectCustomizer”的相同位置指定一个 Groovy`CompilationCustomizer`(例如`ImportCustomizer`)<br/>或者一个完整的 Groovy`CompilerConfiguration`对象。此外,你可以在`ConfigurableApplicationContext.setClassLoader`级别上为你的 bean 设置一个带有自定义<br/>配置的通用`GroovyClassLoader`配置;<br/>这还会导致共享`GroovyClassLoader`使用,因此在<br/>大量脚本 bean 的情况下是值得推荐的(避免每个 Bean 使用一个孤立的`GroovyClassLoader`实例)。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 3.2.3.豆壳豆

这一部分描述了如何在 Spring 中使用豆壳豆。

[Beanshell 主页](https://beanshell.github.io/intro.html)包括以下描述:

```
BeanShell is a small, free, embeddable Java source interpreter with dynamic language
features, written in Java. BeanShell dynamically runs standard Java syntax and
extends it with common scripting conveniences such as loose types, commands, and method
closures like those in Perl and JavaScript.
```

Bean 与 Groovy 相反,支持 BeanShell 的定义需要一些(小的)附加配置。 Spring 中的 BeanShell 动态语言支持的实现是有趣的,因为 Spring 创建了一个 JDK 动态代理,该代理实现了在<`script-interfaces`元素的属性值<lang:bsh>中指定的所有接口(这就是为什么必须在属性的值中至少提供一个接口,因此,当你使用 beanshell 支持的 bean 时,将程序转换为接口)。这意味着对 BeanShell 支持的对象的每个方法调用都要通过 JDK 动态代理调用机制。

现在,我们可以展示一个使用基于 BeanShell 的 Bean 的完全工作的示例,该示例实现了本章前面定义的`Messenger`接口。我们再次展示`Messenger`接口的定义:

```
package org.springframework.scripting;

public interface Messenger {

    String getMessage();
}
```

下面的示例展示了`Messenger`接口的 BeanShell“实现”(我们在这里粗略地使用术语):

```
String message;

String getMessage() {
    return message;
}

void setMessage(String aMessage) {
    message = aMessage;
}
```

下面的示例展示了 Spring XML,它定义了上述“类”的一个“实例”(同样,我们在这里非常松散地使用这些术语):

```
<lang:bsh id="messageService" script-source="classpath:BshMessenger.bsh"
    script-interfaces="org.springframework.scripting.Messenger">

    <lang:property name="message" value="Hello World!" />
</lang:bsh>
```

有关可能需要使用基于 BeanShell 的 bean 的一些场景,请参见[Scenarios](#dynamic-language-scenarios)。

### 3.3.场景

在脚本语言中定义 Spring 托管 bean 将是有益的,这种可能的场景有很多种。本节描述了 Spring 中动态语言支持的两个可能的用例。

#### 3.3.1.脚本 Spring MVC 控制器

可以从使用动态语言支持的 bean 中受益的一组类是 Spring MVC 控制器。在纯 Spring MVC 应用程序中,在很大程度上,通过 Web 应用程序的导航流是由封装在你的 Spring MVC 控制器中的代码决定的。由于 Web 应用程序的导航流和其他表示层逻辑需要更新,以响应支持问题或更改的业务需求,通过编辑一个或多个动态语言源文件,并看到这些更改立即反映在正在运行的应用程序的状态中,很可能更容易实现任何此类所需的更改。

请记住,在 Spring 这样的项目所支持的轻量级架构模型中,你通常的目标是拥有一个非常薄的表示层,应用程序的所有重要业务逻辑都包含在域和服务层类中。 Spring 将 MVC 控制器开发为动态语言支持的 bean,可以通过编辑和保存文本文件来更改表示层逻辑。对这种动态语言源文件的任何更改(取决于配置)都会自动反映在由动态语言源文件支持的 bean 中。

|   |要实现对动态语言支持的<br/>bean 的任何更改的自动“拾取”,你必须启用“刷新 bean”功能。有关此功能的完整处理,请参见[可刷新的咖啡豆](#dynamic-language-refreshable-beans)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

下面的示例显示了使用 Groovy 动态语言实现的`org.springframework.web.servlet.mvc.Controller`:

```
// from the file '/WEB-INF/groovy/FortuneController.groovy'
package org.springframework.showcase.fortune.web

import org.springframework.showcase.fortune.service.FortuneService
import org.springframework.showcase.fortune.domain.Fortune
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.mvc.Controller

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class FortuneController implements Controller {

    @Property FortuneService fortuneService

    ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse httpServletResponse) {
        return new ModelAndView("tell", "fortune", this.fortuneService.tellFortune())
    }
}
```

```
<lang:groovy id="fortune"
        refresh-check-delay="3000"
        script-source="/WEB-INF/groovy/FortuneController.groovy">
    <lang:property name="fortuneService" ref="fortuneService"/>
</lang:groovy>
```

#### 3.3.2.脚本验证器

Spring 应用程序开发的另一个领域是验证领域,该领域可能受益于动态语言支持的 bean 所提供的灵活性。相对于正则 Java,使用松散类型的动态语言(也可能支持内联正则表达式)可以更容易地表示复杂的验证逻辑。

同样,将验证器开发为支持动态语言的 bean,可以通过编辑和保存一个简单的文本文件来更改验证逻辑。任何此类更改(取决于配置)都会自动反映在正在运行的应用程序的执行中,并且不需要重新启动应用程序。

|   |要实现对动态语言支持的<br/>bean 的任何更改的自动“拾取”,你必须启用“可刷新 bean”功能。有关此功能的完整和详细处理,请参见[可刷新的咖啡豆](#dynamic-language-refreshable-beans)。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

下面的示例显示了通过使用 Groovy 动态语言实现的 Spring `org.springframework.validation.Validator`(有关 `validator’接口的讨论,请参见[Validation using Spring’s Validator interface](core.html#validator)):

```
import org.springframework.validation.Validator
import org.springframework.validation.Errors
import org.springframework.beans.TestBean

class TestBeanValidator implements Validator {

    boolean supports(Class clazz) {
        return TestBean.class.isAssignableFrom(clazz)
    }

    void validate(Object bean, Errors errors) {
        if(bean.name?.trim()?.size() > 0) {
            return
        }
        errors.reject("whitespace", "Cannot be composed wholly of whitespace.")
    }
}
```

### 3.4.附加细节

最后一节包含了一些与动态语言支持相关的附加细节。

#### 3.4.1. AOP——为脚本 bean 提供建议

你可以使用 Spring  AOP 框架来建议脚本化的 bean。 Spring  AOP 框架实际上并不知道正在被建议的 Bean 可能是脚本化的 Bean,因此你使用(或旨在使用)的所有 AOP 用例和功能都与脚本化的 bean 一起工作。当你建议使用脚本 bean 时,不能使用基于类的代理。你必须使用[基于接口的代理](core.html#aop-proxying)。

你不限于为脚本 bean 提供建议。还可以用受支持的动态语言编写方面本身,并使用这样的 bean 来建议其他 Spring bean。不过,这确实是对动态语言支持的高级使用。

#### 3.4.2.范围界定

在不是立即显而易见的情况下,脚本 bean 可以以与任何其他 bean 相同的方式进行作用域 Bean。各种`<lang:language/>`元素上的`scope`属性允许你控制底层脚本 Bean 的作用域,就像它对常规 Bean 所做的那样。(默认作用域是[singleton](core.html#beans-factory-scopes-singleton),就像“常规”bean 一样。

下面的示例使用`scope`属性将 groovy Bean 的作用域定义为[prototype](core.html#beans-factory-scopes-prototype):

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">

    <lang:groovy id="messenger" script-source="classpath:Messenger.groovy" scope="prototype">
        <lang:property name="message" value="I Can Do The RoboCop" />
    </lang:groovy>

    <bean id="bookingService" class="x.y.DefaultBookingService">
        <property name="messenger" ref="messenger" />
    </bean>

</beans>
```

有关 Spring 框架中范围支持的完整讨论,请参见[Bean Scopes](core.html#beans-factory-scopes)中的[IOC 容器](core.html#beans)。

#### 3.4.3.`lang`XML 模式

Spring XML 配置中的`lang`元素将用动态语言(如 Groovy 或 BeanShell)编写的对象作为 Spring 容器中的 bean 公开。

在[动态语言支持](#dynamic-language)中全面介绍了这些元素(以及动态语言支持)。有关此支持和`lang`元素的详细信息,请参见该部分。

要使用`lang`模式中的元素,你需要在 Spring XML 配置文件的顶部具有以下前导码。以下代码片段中的文本引用了正确的模式,因此你可以使用`lang`名称空间中的标记:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">

    <!-- bean definitions here -->

</beans>
```

### 3.5.更多资源

下面的链接指向关于本章中引用的各种动态语言的更多参考资料:

* [Groovy](https://www.groovy-lang.org/)主页

* [BeanShell](https://beanshell.github.io/intro.html)主页

* [JRuby](https://www.jruby.org)主页